Saturday, October 25, 2008

Find column number based on field header - awk


One of my application generates a raw file where number of fields (columns) is more than 40. So to know the field position for a particular field was tough.

This is a sample file to show how we can find the column number of a particular column by using the column header.

$ cat rawfile.txt
#Fields date time loc my-det nsv-ps max-auto-s help-n min-new
Sat-Oct-25 02:00 IN o1asbi09 9076 1000 - 12
Sat-Oct-25 02:30 IN o1asbi09 4073 1000 - 10
Sat-Oct-25 03:00 IN o1asbi09 6186 1000 - 10
Sat-Oct-25 02:30 IN o1asbi09 7063 1000 - 12
...

S0 to find the column number of the field where the column header is "max-auto-s", the awk one liner would be:

$ awk '
END { if (!f++) print "pattern not found" }
/^#Fields/{ for(i=1;i<=NF;i++){
if ($i ~ "max-auto-s")
{print "[line="NR,"column="i-1"]", f++} }
}' rawfile.txt

Output:
[line=1 column=6] 0

Related post:

Print field based on header using awk

No comments:

© Jadu Saikia www.UNIXCL.com