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!

Delete a single line & regex

Status
Not open for further replies.

pip56789

Technical User
Dec 9, 2011
2
US
Hi, I'm totally new to awk, so thanks in advance for your help.

I want to make a csv file out of a text file I've exported from a database I want to do two things:
1. Change pipes ("|") to commas (",") to make a text file into CSV
2. Remove the second line of the file, which is useless junk.

Here's what I have so far to accomplish #1. I'm struggling on #2. Help?

function pull() {
cat $@ | awk '{gsub(/\|/,","); print;}' > $@.csv;
}


 
You have to define FS, OFS and say to awk, that it should process lines except of nr=2:
Code:
[COLOR=#0000ff]# Run: awk -f pip56789.awk pip56789_file.txt[/color]
[COLOR=#6a5acd]BEGIN[/color] {
  [COLOR=#6a5acd]FS[/color]=[COLOR=#ff00ff]"|"[/color]
  [COLOR=#6a5acd]OFS[/color]= [COLOR=#ff00ff]","[/color]
}
[COLOR=#6a5acd]NR[/color] != [COLOR=#ff00ff]2[/color] {
  [COLOR=#804040][b]print[/b][/color] [COLOR=#6a5acd]$1[/color][COLOR=#6a5acd],[/color] [COLOR=#6a5acd]$2[/color][COLOR=#6a5acd],[/color] [COLOR=#6a5acd]$3[/color]
}
Then it makes from this input file
Code:
Field1 | Field2 | Field3
# This is junk
1| 2 | 3
foo | bar | baz
this output
Code:
Field1 , Field2 , Field3
1, 2 , 3
foo , bar , baz
 
Replace this:
cat $@ | awk '{gsub(/\|/,","); print;}' > $@.csv
with this:
awk '{gsub(/\|/,",")}FNR!=2' $@ > $@.csv

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi

Just one thing. That $@.csv as output file looks bad. [tt]$@[/tt] expands to the list of input parameters, so is Ok to use it as list of input file names, but not for output. Maybe "$*.csv", also a strange one, but at least will not result an ambiguous redirect error in case of multiple parameters.


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top