Platinum Platinum - 1 year ago 111
Bash Question

Print columns in for loop in awk wrt variable value

I am trying to count number of occurrences of a word "is" using

through sample program below:

awk '
BEGIN { count = 0; word="is"; out=$ }
/word/ {
for (i=1; i<=NR; i++) {
if ($(i) == word) count++;
END {print "Found word " word count " no of times"}
' data.txt

But here the problem is
is not being interpreted as column number.
Can you please suggest what should be written in place of
to reference the column number (dynamic) as per value of
in that line?

Answer Source

i is the field or column number (1, 2, 3, ...) and $i is the value in that field:

$ echo This is it|awk '{for(i=1; i<=NF; i++) print i" "$i}'
1 This
2 is
3 it

So your program:

$ cat test.awk
    count = 0
    for (i=1; i<=NF; i++) 
        if ($(i) == word) 
    print "Found word " word" "count " no of times"
$ echo This is it|awk -f test.awk
Found word is 1 no of times
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download