Use stdin and you won't have issue with wc
printing filename
wc -l < countlines.py
Frage
I want to get only the number of lines in a file: so I do:
$wc -l countlines.py
9 countlines.py
I do not want the filename, so I tried
$wc -l countlines.py | cut -d ' ' -f1
but this just echo empty line.
I just want number 9
to be printed
Lösung
Use stdin and you won't have issue with wc
printing filename
wc -l < countlines.py
Andere Tipps
You can also use awk
to count lines. (reference)
awk 'END { print NR }' countlines.py
If your file doesn't ends with a \n
(new line) the wc -l
gives a wrong result. Try it with the next simulated example:
echo "line1" > testfile #correct line with a \n at the end
echo -n "line2" >> testfile #added another line - but without the \n
the
$ wc -l < testfile
1
returns 1. (The wc
counts the number of newlines (\n
) in a file.)
Therefore, for counting lines (and not the \n
characters) in a file, you should to use
grep -c '' testfile
e.g. find empty character in a file (this is true for every line) and count the occurences -c
. For the above testfile
it returns the correct 2.
Additionally, if you want count the non-empty lines, you can do it with
grep -c '.' file
Don't trust wc
:)
Ps: one of the strangest use of wc
is
grep 'pattern' file | wc -l
instead of
grep -c 'pattern' file
As an alternative, wc won't print the file name if it is being piped input from stdin
$ cat countlines.py | wc -l
9
yet another way :
cnt=$(wc -l < countlines.py )
echo "total is $cnt "
Piping the file name into wc
removes it from the output, then tr
anslate away the whitespace:
wc -l <countlines.py |tr -d ' '
Use awk like this:
wc -l countlines.py | awk {'print $1'}