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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

loop through file - parse lines based on field delimiter

Status
Not open for further replies.

southbeach

Programmer
Jan 22, 2008
879
US
I have this file:
Code:
master::XXX887YY::ACCOUNT NAME ONE:some.domain.com::eof
::ABC123ABC::ACCOUNT NAME TWO:some.domain.com::eof
master::SXYZZ823::ACCOUNT NAME THREE:some.domain.com::eof
::CCD0932YFD::ACCOUNT NAME FOUR:some.domain.com::eof
foo:bar:foobar:foo:ACCOUNT NAME FIVE:some.domain.com:some.domain.com:eof
test:test:testbar:testing:TEST NAME:test.domain.com:test.domain.com:eof

I can be of any number o lines but same number of columns. I need to
1. Read through each line
2. explode the lines based on field delimiter

Notice that the field delimiter is :

How can I do this?

Thank you all for your assistance!




--
SouthBeach
The good thing about not knowing is the opportunity to learn - Yours truly, 2008.
 
For simple parsing: man cut
For more complex processing: man awk

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
I find this is the easiest for something like that...

Code:
#!/bin/ksh

# Set delimiter (IFS = Inter Field Separator)
IFS=:

while read FIELD1 FIELD2 FIELD3 FIELD4 FIELD5 REMAINDER
do
[indent]# Each field in the file has been assigned the variable names after the "read"
print "FIELD1 = ${FIELD1}"
print "FIELD2 = ${FIELD2}"
print "FIELD3 = ${FIELD3}"
print "FIELD4 = ${FIELD4}"
print "FIELD5 = ${FIELD5}"
print
[/indent]
done

Apologies for any typos, I didn't test it. [bigsmile]

 

Or you can check out the script I posted in the article: Quick and Dirty Unix CSV File Browser
[3eyes]



----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
Oops, I did have a code error. The final [tt]done[/tt] should be like this...

Code:
#!/bin/ksh

# Set delimiter (IFS = Inter Field Separator)
IFS=:

while read FIELD1 FIELD2 FIELD3 FIELD4 FIELD5 REMAINDER
do
[indent]# Each field in the file has been assigned the variable names after the "read" 
print "FIELD1 = ${FIELD1}" 
print "FIELD2 = ${FIELD2}" 
print "FIELD3 = ${FIELD3}" 
print "FIELD4 = ${FIELD4}" 
print "FIELD5 = ${FIELD5}" 
print [/indent]
[b]done < file.txt[/b]


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top