Identifying the column number

I'd like to be able to identify in which column a string occurs. So far I know that I can tell how many columns there are and how to return a specific column:

$ sar -r | grep 'kbswpcad' | awk 'NF = 9 { print $NF }'
%swpused

I've even managed to get the columns to output to an array but I think this is over complicated:

$ sar -r | head -3 | tail -1 | tr -s [:blank:] " " | awk '{ split($0, head, " ") } END { for (i in head) print i, " : "head }'
4  : %memused
5  : kbbuffers
6  : kbcached
7  : kbswpfree
8  : kbswpused
9  : %swpused
10  : kbswpcad
1  : 00:00:01
2  : kbmemfree
3  : kbmemused

Using the above I still can't do a string check on the array element.

So, in short, how find out which column %swpused is in?

Thanks in advance :slight_smile:

go through the fields.

sar -r | grep 'kbswpcad' | awk '{ for(i;i<=NF;i++){
    if ($i ~ /swpused/) { print i } }
}'

Brilliant! Thanks Ghostdog74 :slight_smile: