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: sed -n '$=' prints how many lines a file has

Sed
~/tips/tip-sed-count-lines

sed -n '$=' access.log

Print the number of lines in a file, or the line numbers of matches, with sed.

Most people reach for wc -l to count lines, and that is the right call. Still, sed can do it too, and the trick is a nice way to see how sed addresses work.

Try this:

sed -n '$=' access.log

$ is the address of the last line, and = is the command that prints the current line number. -n turns off the normal printing of every line, so you get one number and nothing else. Put a pattern in front to count only matching lines, as in sed -n '/error/=' app.log, which prints the line number of every match instead.

A caveat: if the file has no trailing newline, wc -l and sed can differ by one. For a simple total, wc -l is shorter. The sed form pays off once you combine it with an address, because it can print the line numbers of matches for you.

One more detail: the same address trick prints the last line only with sed -n '$p'. Together with = it shows that sed commands are small building blocks, and addresses decide which lines they act on.

Further reading: GNU sed manual, = command

More Sed tips echo 'hello world' | sed 's/.*/\U&/' printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5' sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf sed -n '210,218p' /etc/nginx/nginx.conf sed -i.bak 's/old-host/new-host/g' config.txt All Sed tips (6) All topics

Link