brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: wc -l < file gives you only the number, without the file name

Linux
~/tips/tip-shell-wc-l-stdin-number-only

wc -l < access.log

Prints just the line count of a file, so you can use it directly in a script.

A small thing that bugs me: wc -l access.log prints the count and then the file name. Great on screen, clumsy in a script where all you want is the number.

The trick is to hand wc the file on standard input instead of as an argument. With no file name to report, it prints only the count:

wc -l < access.log

That makes it easy to store the result in a variable and compare it, without piping through cut or awk to chop off the name:

lines=$(wc -l < access.log)
if [ "$lines" -gt 10000 ]; then echo "log is getting big"; fi

The same works for the other counters: wc -w < notes.txt for words and wc -c < image.png for bytes. And because the count comes from standard input, you can put any command in front of it, like ls /mnt/user/appdata | wc -l to count the folders in there.

The caveat is in the man page wording. -l prints the newline count, not the line count. Those are the same thing as long as the file ends with a newline, which almost every tool writes. A file whose last line has no newline at the end gets counted one short: printf 'a\nb' | wc -l prints 1, even though you can see two lines. If an exact count matters and the file comes from somewhere you don’t control, keep that in mind before you trust the number.

Further reading: wc(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link