← All commands
THE COMMAND REFERENCE

nl

Number the lines of a file.

Last updated

BusyBox

Implementation-level reference; examples are not certified for every installed version.

Overview

nl prints a file with a line number in front of each line. By default it numbers only lines that are not empty, and it puts a tab between the number and the text. For numbering every line, use -ba; cat -n is the shorter way when that is all you need.

Background

The nl utility first appeared in AT&T System V Release 2 UNIX, according to the macOS manual. Today the name covers GNU nl, the nl that macOS ships, and the nl applet in BusyBox. They agree on the default numbering and on -b, -s and -w.

Examples

Number the lines of a file:

nl notes.txt

Number every line, including empty ones, with -b a:

printf 'one\n\ntwo\n' | nl -b a

Number only the lines that are not empty, which is the default, written out as -b t:

printf 'one\n\ntwo\n' | nl -b t

Use a dot and a space between the number and the text with -s:

nl -s'. ' notes.txt

Use a narrower number column with -w:

nl -w 2 notes.txt

Options

-b
Choose which lines to number: a for all, t for non-empty ones, n for none.

-s
Put this text between the number and the line.

-w
Set the width of the number column.

Common mistakes

By default blank lines are not numbered and are not counted, so the numbers can look as if they skip. Add -b a to number them. Line numbers are padded with spaces, so a script that reads them should split on whitespace rather than counting characters.

Portability

Only -b, -s and -w are in the Common examples. Section and page handling options differ, and the padding of the number column is not the same on every system, so the examples compare output after collapsing blanks. The Common examples were executed on GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).

About BusyBox nl

BusyBox bundles nl as an applet, and anything beyond the common options depends on how it was built. This page's examples ran on BusyBox 1.37.0.

BusyBox notes

BusyBox nl supports -b, -s and -w. Other options depend on the build.

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.