AWK Find field number


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


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! 🙂


Now for a real life demo. 😉

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


[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,

    • 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 *