using variable in awk

Hello I would like to count number of words with specific lengths. I’m using this command.

awk 'length == 2' mydict.txt | wc -l

this code gives what I want but if try to put variable instead of number 2 it doesnt work. The code is like this

awk 'length == $var' mydict.txt | wc -l

and terminal prints 0. What can I do

>Solution :

Variables won’t get expanded in single quotes (').

Normally, you could simply use double quotes ("), but for awk, this is not a good solution because it will lead to problems with little more complicated awk code.

Better assign an awk variable with -v:

awk -v var="$var" 'length == var' mydict.txt | wc -l

However, there is no need for wc -l, awk can do this for you:

awk -v var="$var" 'length == var{n++} END{print n}' mydict.txt

You could also use grep -c:

grep -c "^.\{$var\}\$" mydict.txt

Leave a Reply