Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading