Platinum Platinum - 3 months ago 11
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

awk
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
$(i)
is not being interpreted as column number.
Can you please suggest what should be written in place of
$(i)
to reference the column number (dynamic) as per value of
i
in that line?

Answer

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
BEGIN { 
    count = 0
    word="is"
} 
{
    for (i=1; i<=NF; i++) 
        if ($(i) == word) 
            count++
} 
END {
    print "Found word " word" "count " no of times"
} 
$ echo This is it|awk -f test.awk
Found word is 1 no of times
Comments