Sunday, March 23, 2008

Print field based on header - AWK


$ cat student.vi.out
FName:DOB:Rank:Result
Jack:1982:A+:Pass
Bin:1981:B-:Fail
Nin:1982:A:Pass
Lenin:1983:A+:Pass
Hope:1982:B+:Pass

We can print the 3rd field i.e. "Rank" field as below:

$ awk '{print $3}' FS=: student.vi.out

But if you are not sure whether "Rank" field is at 3rd place or 4th place or 5th(in case of a big file with so many fields), but you know that the field has the heading named as "Rank", this is how you can print that particular field:

$ awk -v header="Rank" '
BEGIN { FS=":"; c=0 }
NR == 1 { for (i=1;i<=NF;i++) { if ($i==header) { c=i }} }
NR > 1 && c>0 { print $c }
' student.vi.out

Output:
A+
B-
A
A+
B+

2 comments:

ciruzzo said...

Thank you so much for this

Irene Santomé said...

It seems very useful, but... what if I want to extract two columns i.e. "Rank" and "Result" in the same output?

thank you so much!

© Jadu Saikia www.UNIXCL.com