Issue
I want to get a number of python files on my desktop and I have coded a small script for that. But the awk command does not work as is have expected. script
ls -l | awk '{ if($NF=="*.py") print $NF; }' | wc -l
I know that there is another solution to finding a number of python files on a PC but I just want to know what am i doing wrong here.
Solution
ls -l | awk '{ if($NF=="*.py") print $NF; }' | wc -l
Your code does count of files literally named *.py
, you should deploy regex matching and use correct GNU AWK
syntax, after fixing that, your code becomes
ls -l | awk '{ if($NF~/[.]py$/) print $NF; }' | wc -l
note [.]
which denote literal .
and $
denoting end of string.
Your code might be further ameloriated, as there is not need to use if
here, as pattern-action will do that is
ls -l | awk '$NF~/[.]py$/{ print $NF; }' | wc -l
Morever you might easily implemented counting inside GNU AWK
rather than deploying wc -l
as follows
ls -l | awk '$NF~/[.]py$/{t+=1}END{print t}'
Here, t
is increased by 1
for every describe line, and after all is processed, that is in END
it is print
ed. Observe there is no need to declare t
variable in GNU AWK
.
Answered By - Daweo Answer Checked By - David Goodson (WPSolving Volunteer)