Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use sed to split a string

Status
Not open for further replies.

alhassani54

Programmer
Aug 1, 2002
27
0
0
GB
Hi

I have a string which contain "003900" and the string could have one or many of "003900". I would like to split the string into files depends on the number of "003900" in the string.

For example
rec="0039001234 5 6 0039002345 6 8 90039001238"
File1=0039001234 5 6
File2=0039002345 6 8 9
File3=0039001238

I have tried to use sed but it did not work because the spaces in rec and the spaces are required

rec="0039001234 5 6 0039002345 6 8 90039001238"
set -- `echo $rec | sed 's/003900/ 003900/g'`
integer cnt1=1
until (($# == 0))
do
a[$cnt1]=$1
print "a[$cnt1]="${a[$cnt1]}
#print ${a[$cnt1]} > /ics/tmp/kah[$cnt1]
print ""
shift
cnt1=cnt1+1
done

To run the script
Rec=0039001234 5 6 0039002345 6 8 90039001238

a[1]=0039001234
a[2]=5
a[3]=6
a[4]=0039002345
a[5]=6
a[6]=8
a[7]=9
a[8]=0039001238

Please can you help?

Thanks
 
Hi

Code:
rec="0039001234 5 6 0039002345 6 8 90039001238"
[red]IFS='
'[/red]
set -- `echo $rec | sed 's/003900/[red]\n[/red]003900/g'`
integer cnt1=1
until (($# == 0))
do
        a[$cnt1]=$1
        print "a[$cnt1]="${a[$cnt1]}
        #print ${a[$cnt1]} > /ics/tmp/kah[$cnt1]
        print ""
        shift
        cnt1=cnt1+1
done

Feherke.
 
Code:
#!/bin/ksh
rec="0039001234 5 6 0039002345 6 8 90039001238"
i=1
echo $rec | sed 's/003900/\
003900/g' | while read line
do
    if [[ -n "$line" ]]
    then
            echo "$line" > alhassani54_file$i
            ((i=i+1))
    fi
done

Note that the line feed in the sed expression is intentional.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top