AWK Find field number

[problem]

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

[/problem]

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

[/solution]

[example]

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

[/example]

[reference]

[tags], Unix Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

2 Replies to “AWK Find field number”

    1. 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 *