2

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?

αғsнιη
  • 35,660
  • not that the commnad you came with, it doesn't do what you said "count number of words with specific length", it counts the number of lines having 2 *characters* length only not words. – αғsнιη Jan 11 '22 at 16:20

1 Answers1

5

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
terdon
  • 100,812
pLumo
  • 26,947