AWK Find field number

Problem

Ever needed to print out one column with awk, but do not know the field number?



Solution

Here I’m running df and looking for a field with “Used” in it:

df -k | head -1 | awk ' {      for(i=1; i< NF;i++) {         if($i ~ /Used/) {             print "# field "i         }      }} '

So stop counting columns and just use the code! 🙂



Example


Now for a real life demo. 😉


[marcus@bree marcus]$ df -k | head -1
Filesystem 1K-blocks Used Available Use% Mounted on
[marcus@bree marcus]$ df -k | awk ' {
for(i=1;i < NF;i++) {
if($i ~ /Used/) { print "# field "i }
}
} '
# field 3



Reference

[tags], Unix Coding School[/tags]



Comments (2)

  1. Rama

    I have to search a string like Annual Income, which has a space. How do we handle this.

    Thank you,
    Rama

    • admin

      Hi Rama, if you wanted to split out by column – but ignore Annual Income, then perhaps use sed and pipe through awk. Like this sed 's/Annual Income/Annual-Income/g' filename | awk ….

Leave a Reply

Your email address will not be published. Required fields are marked *