NL Command - Number Lines of Files | Online Free DevTools by Hexmos

Number lines of files with the NL command. Learn how to use nl to number lines from STDIN or files, with options for different numbering styles.

NL Command - Number Lines of Files

The nl command is a powerful utility in Unix-like operating systems used for numbering lines of files. It provides more flexibility and control over line numbering compared to simpler methods like cat -n.

Number Lines from Standard Input

You can pipe the output of other commands to nl to number their lines. This is particularly useful in shell scripting for processing text streams.

# Number lines given to nl(1) via STDIN.
printf "Here\nis\nsome\nexample\ntext." | nl

Number Lines from Files

The primary use of nl is to number the lines of one or more specified files. The -b a option ensures that all lines are numbered, regardless of whether they are empty or not.

# Number (all) lines given to nl(1) via provided file(s).
nl -b a /path/to/file

Alternative to nl Command

For basic line numbering, the cat -n command offers a more portable and often simpler alternative. However, nl provides advanced options for customizing the numbering format, starting number, and more.

# The above can also be achieved with cat(1), which is perhaps more portable:
cat -n /path/to/file

Understanding NL Command Options

The nl command offers various options to customize line numbering. For instance, you can control the numbering style (e.g., numeric, logical), the starting number, the increment, and the width of the number field. Refer to the official documentation for a comprehensive list of options.

Further Resources