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: nl -ba puts line numbers in front of every line, blank ones too

Linux
~/tips/tip-shell-nl-ba-number-lines

nl -ba -w 4 -s ': ' /etc/hosts

Adds line numbers to the output of a file or command, numbering empty lines as well.

When someone asks me which line of a config file is the problem, I want numbers next to the text. cat -n does it, and nl does it with more control.

nl -ba -w 4 -s ': ' /etc/hosts

nl writes its input with line numbers added. The -b option picks the numbering style for the body, and -ba means number all lines. By default only non-empty lines are numbered, which is the part that surprises people when the numbers do not match the editor.

-w sets the width of the number field, which is 6 by default, and -s sets the separator between the number and the text, a tab by default. In the example the lines come out as 1: 127.0.0.1 localhost.

It also works on a pipe, so you can number the output of another command, for example to refer to a line in a chat message:

journalctl -u ssh -n 20 --no-pager | nl -ba

The caveat is that -w and -s each need a value, and if you forget it, nl takes the next word as that value and the command does something odd. Also, nl understands logical pages marked by special delimiter lines, which only matters for unusual input, but it explains why a file with lines like \:\:\: numbers differently. For a plain “number everything” job, cat -n is shorter, and nl is for when the format matters.

Further reading: GNU Coreutils: nl invocation

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