nl(1)
Number the lines of files, outputting them with line numbers prepended.
Synopsis
nl [OPTION]... [FILE]...Description
The nl command reads files (or standard input) and writes them to standard output with line numbers added. It is useful for numbering code, logs, or any text where line references are helpful. Unlike cat -n, nl offers sophisticated control over which lines get numbered and how they appear.
By default, nl numbers only non-blank lines and uses a tab separator. It can reset numbering at page breaks and apply different numbering schemes to headers, body, and footer sections of input.
Common options
| Flag | What it does |
|---|---|
-b TYPE | Number only lines of type: a (all lines), t (non-empty lines, default), n (no lines), p (lines matching regex) |
-n TYPE | Set number format: ln (left-justified), rn (right-justified, default), rz (right-justified with zeros) |
-v NUM | Set starting line number (default is 1) |
-i NUM | Set increment between line numbers (default is 1) |
-w WIDTH | Set width of the line number field (default is 6) |
-s STR | Use string as separator between number and text (default is tab) |
-p | Do not reset line number at page breaks (marked by \f) |
-h TYPE | Set numbering for header lines (sections before first \f) |
-d STR | Set page break delimiters (default is \f for section start) |
-l NUM | Number only every NUMth blank line (used with -ba) |
Examples
Number non-blank lines in file.txt with default format (right-aligned in 6-char field, tab separator)
nl file.txtNumber all lines including blank ones
nl -ba file.txtNumber lines left-justified (instead of right-justified)
nl -nln file.txtUse narrower 3-character field and ': ' as separator between number and text
nl -w3 -s': ' file.txtStart numbering at 100 and increment by 5 for each line
nl -v100 -i5 file.txtNumber only lines starting with # (regex matching)
nl -bp'^#' file.txtNumber all lines of a log file including blanks and pipe to pager
cat logfile | nl -ba | lessNumber with zero-padding in 4-character field (e.g., 0001, 0002, 0003)
nl -nrz -w4 script.sh