Linux Command: nl
Number lines of files
The nl command numbers lines of files, providing more formatting control than cat -n. It supports different numbering styles, formats, and can selectively number only non-empty lines or lines matching specific patterns. nl divides input into logical sections (header, body, footer) and can apply different numbering rules to each section. This makes it useful for formatting source code listings, reports, and documents. While cat -n provides basic line numbering, nl offers customizable number format, width, separator string, and selective numbering โ making it the better choice for producing formatted, professional output.
Syntax
nl [OPTION]... [FILE]...Key Options
-b aโ Number all lines including blank lines-b tโ Number only non-empty lines (default)-b pโ Number only lines matching a regex pattern-n lnโ Left-justified line numbers-n rzโ Right-justified with leading zeros-wโ Set width of line number field
Examples
Number all lines
nl -ba script.shOutput: 1 #!/bin/bash
2
3 echo "Hello"
Number with leading zeros
nl -nrz -w4 data.txtOutput: 0001 First line
0002 Second line
Number only non-empty lines
nl config.confPro Tips
- nl -s'. ' -w2 creates numbered lists like 1. First item. Use in scripts to format output.
- cat -n is simpler but numbers all lines with fixed format. nl offers customizable numbering style, width, separator, and selective numbering.
- By default, nl does not number blank lines. Use -ba if you need all lines numbered (like cat -n behavior).
Learn more: Full nl reference โ