Question

I have a pipe delimited file that contains many data fields. I am trying to use gawk separate them. The log likes this:

United States|San Francisco|CA|...goes on...
Germany|Quebec City|Quebec|...goes on...

The output format would look like:

Country: United States
City: San Francisco
State: CA
...goes on...

The question is...is there any way I can auto increase $1 all the way to $15? Skip $16 then auto increase again? I just don't want to hard code my gawk script with this:

print "Country:\t", $1
print "City:\t", $2
print "State:\t", $3
Was it helpful?

Solution

You can use a for loop and an if condition:

awk -v FS='|' '
   BEGIN{split("country;city;state",a,";")}
   {for (i=1;i<NF;i++) if (i != 16) print a[i],i}' input

OTHER TIPS

It's not entirely clear, but if your truncated input looks something like:

United States|San Francisco|CA|Salem|OR...

and you are just trying to enumerate city/state pairs, you can certainly do:

for( i = 2; i <= NF ;i+=2 ) {
  print "City:\t", $i
  print "State:\t", $(i+1)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top