What it does
nl reads a file and prepends line numbers. Unlike
cat -n, it allows control over which lines are numbered
(e.g., non-blank lines only, all lines, or specific logical sections).
How it works (mechanical)
nl processes input line by line and prefixes a formatted number field. It can define logical sections (header/body/footer) separated by markers, and apply numbering rules to each section independently.
-bcontrol numbering of body lines-hcontrol numbering of header lines-fcontrol numbering of footer lines-wset width of number field-sset separator between number and text
10 Practical Examples
# 1) Number all non-blank lines (default) nl file.txt
# 2) Number ALL lines (including blanks) nl -ba file.txt
# 3) Number only non-empty lines (explicit) nl -bt file.txt
# 4) Set custom number width nl -w 4 file.txt
# 5) Change separator to " | " nl -s " | " file.txt
# 6) Number lines in a pipeline grep ERROR logfile | nl
# 7) Start numbering at a specific value nl -v 100 file.txt
# 8) Increment by 5 nl -i 5 file.txt
# 9) Restart numbering per logical page nl -p file.txt
# 10) Compare with cat -n cat -n file.txt
Notes & Gotchas
- Blank lines: default behavior does not number blank lines.
- Section markers: logical sectioning requires special delimiters.
- cat -n vs nl:
cat -nis simpler;nlis more configurable. - Formatting width: large files may require wider number fields.
Historical Context
nl has been part of Unix text processing tools for decades. It reflects the classic design philosophy: small, composable utilities that perform one job well and integrate into pipelines.
Related Commands
- cat -n — simple line numbering
- awk '{print NR, $0}' — programmable numbering
- sed '=' — print line numbers separately
- pr — formatted printing with headers