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

how do i separate fields delimited by pipes (¦)?

Status
Not open for further replies.

jaykjoe

Programmer
Jan 15, 2002
10
US
Hello,

I have a spooled SQL file that I need to separate the fields delimited by pipes using awk or sed. There can be leading and trailing spaces in between pipes. How can I just extract the field itself and not any spaces.

For example, file(line) looks like:

01 | I | am | stuck |on| this.

field1=01
field2=I
field3=am
field4=stuck
field5=on
field6=this.

Any help would be appreciated. Thanks.

Jason
 
Try this
Code:
{
  gsub (/ /,"")
  split($0,aa,"|")
  print "field2=" aa[1]
  print "field3=" aa[2]
  print "field4=" aa[3]
  print "field5=" aa[4]
  print "field6=" aa[5]
  print "field6=" aa[6]
}
Hope this helps.
CaKiwi
 
Thanks CaKiwi. However, I happen to have some fields that are blank and it deletes them.

For example:

01 | | am | stuck |on| this.

This line would produce results:

field1=01
field2=am
field3=stuck
field4=on
field5=this.

Field2 is ignored and everything is shifted.

Any way I can modify it so I can include those blank items?


Thanks.

Jason
 


extract the needed fields assuming FS="|" and then 'trim' the leading the trailing blanks from the field itself. This will NOT cause the "embedded" blanks being trimmed.

function trim(str)
{
nsub1=sub("^[ ]*", "", str);
nsub2=sub("[ ]*$", "", str);
return (str);
}

vlad
 
To complete vgersh99's thought ...
Code:
BEGIN {FS="|"}
{
  for (i=1;i<=NF;i++) {
    sub(/^ */,&quot;&quot;,$i)
    sub(/ *$/,&quot;&quot;,$i)
    print &quot;field1=&quot; $i
  }
}
Hope this helps. CaKiwi
 
do you think I can make it to the &quot;Top 10&quot; with this thread? ;)

vlad
 
I am a big fan of your work vgersh: you helped me a lot
if you want to take the blame for that.
 

thanks - guilty as charged!

Lemme reciprocate here....

And I in turn appreciate your post here and on comp.lang.awk and the sense of humor as in:

> Us backwoods folk don't know nuthin 'bout that.
> We does what we wants when we wants it.

What a happy, HAPPY family we have.....

thanks for kind words

vlad
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top