Chris Hadley
Chris Hadley

Reputation: 89

Find the number of occurences of a word using awk and a variable

I am trying to find the number of fields that contain the word entered by the user. I do not know the syntax to use the variable in my awk statement. If I just use a literal string of $i == "Washington" it works, but I need it to use the input. When I try this it returns nothing:

    <code>
read Choice
    awk '{ 
         for (i=1;i<=NF;i++)
             if ( $i == "$Choice")
             c++
         }
    END{
    print c}' DC_Area.csv
    </code>

Upvotes: 0

Views: 40

Answers (1)

jayant
jayant

Reputation: 2389

Shell variables are not visible in awk. That's why the code in the OP doesn't work. Use the -v option to pass on shell variables to awk.

Try

read Choice
awk -v Choice="$Choice" '{ 
     for (i=1;i<=NF;i++)
         if ( $i == Choice)
         c++
     }
END{
print c}' DC_Area.csv  

Upvotes: 3

Related Questions