$linuxjunkies
>

nl(1)

Number the lines of files, outputting them with line numbers prepended.

UbuntuDebianFedoraArch

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

FlagWhat it does
-b TYPENumber only lines of type: a (all lines), t (non-empty lines, default), n (no lines), p (lines matching regex)
-n TYPESet number format: ln (left-justified), rn (right-justified, default), rz (right-justified with zeros)
-v NUMSet starting line number (default is 1)
-i NUMSet increment between line numbers (default is 1)
-w WIDTHSet width of the line number field (default is 6)
-s STRUse string as separator between number and text (default is tab)
-pDo not reset line number at page breaks (marked by \f)
-h TYPESet numbering for header lines (sections before first \f)
-d STRSet page break delimiters (default is \f for section start)
-l NUMNumber 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.txt

Number all lines including blank ones

nl -ba file.txt

Number lines left-justified (instead of right-justified)

nl -nln file.txt

Use narrower 3-character field and ': ' as separator between number and text

nl -w3 -s': ' file.txt

Start numbering at 100 and increment by 5 for each line

nl -v100 -i5 file.txt

Number only lines starting with # (regex matching)

nl -bp'^#' file.txt

Number all lines of a log file including blanks and pipe to pager

cat logfile | nl -ba | less

Number with zero-padding in 4-character field (e.g., 0001, 0002, 0003)

nl -nrz -w4 script.sh

Related commands