Score:2

using variable in awk

cx flag

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нιη avatar
cn flag
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_.
Score:5
in flag

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
kekekeke avatar
cx flag
Thanks a lot for the answers it helped a lot.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.