When analysing source code, reviewing configuration files, or preparing script outputs for documentation and technical debugging in Linux, prepending line numbers makes referencing specific lines significantly easier. While many text editors and pagers (like less -N) provide visual numbering, producing persistent numbered files directly in shell pipelines requires a command-line filter.
While the standard cat -n command is frequently used for simple numbering, the specialised nl (Number Lines) utility provides far greater formatting flexibility, allowing administrators to control numbering styles, exclude or count blank lines, set custom number separators, and configure section-based numbering.
Basic Line Numbering with nl
To number lines of a text file using standard default formatting:
nl server.conf
By default, nl reads the target file and numbers all non-empty lines, padding numbers with tabs and aligning them neatly on the left margin. Like standard Unix text filters, nl can also accept input directly from standard input via shell pipes:
grep -i "error" /var/log/syslog | nl
Controlling Blank Line Numbering with the -b Flag
One of the key advantages of nl over cat -n is granular control over blank line handling using the -b (body numbering) option:
- Number all lines including blanks (
-b a):
This numbers every single line sequentially, identical tonl -b a config.yamlcat -n. - Number only non-empty lines (
-b t):
This is the default mode, where blank lines remain visible but unnumbered.nl -b t config.yaml - Number lines matching a regular expression (
-b p<regex>):
This instructsnl -b p"^server" nginx.confnlto apply line numbers only to lines starting with the word “server”, leaving other lines unnumbered. - Suppress line numbering in the body (
-b n):
Leaves the body section unnumbered.nl -b n file.txt
Customising Number Formatting, Width, and Padding
You can adjust the appearance and alignment of line numbers using dedicated formatting flags:
- Adjust digit field width (
-w): By default,nlreserves 6 spaces for line numbers. To set a custom width (such as 3 digits):nl -w 3 script.sh - Number formatting styles (
-n):ln: Left-justified, no leading zeros (e.g.1).rn: Right-justified, no leading zeros (default, e.g.1).rz: Right-justified, with leading zeros (e.g.000001).
The command above outputs numbers in a uniform 4-digit zero-padded format (such asnl -n rz -w 4 inventory.txt0001,0002). - Custom delimiter separator (
-s): By default,nlseparates line numbers from file text with a tab character. You can replace the tab with a custom string (such as a colon or pipe):nl -s ": " -w 3 app.log
Managing Increment Values and Starting Numbers
When appending lines or synchronising code snippets across disparate documents, you can specify custom starting numbers and step increments:
nl -v 100 -i 5 data.csv
In this example, -v 100 sets the starting line number to 100, while -i 5 increments successive lines by 5 (producing 100, 105, 110, and so forth).