nl – Add Line Numbers to Each File

The nl command is a Linux command-line utility used to add line numbers to a file. This command is useful for adding line numbers to files that do not have them, making it easier to reference specific lines of code or text. It is also helpful for printing files with line numbers.

Overview

The nl command can be used in a variety of ways. To add line numbers to a file, simply enter the following command:

nl filename

This will add line numbers to the specified file and output the result to the terminal.

By default, nl will number all lines in the file, including blank lines. To exclude blank lines from the numbering, use the -b option followed by a type:

nl -b type filename

The type can be a for numbering all lines, t for numbering only non-blank lines, or n for not numbering any lines.

To specify the line number format, use the -n option followed by a format:

nl -n format filename

The format can be ln for left justified line numbers, rn for right justified line numbers, or rz for right justified line numbers with leading zeros.

Options

The following table lists all the available options for the nl command:

Option Description
-b type Specify which lines to number (a for all, t for non-blank, n for none)
-i number Set the line number increment to number
-n format Set the line number format (ln, rn, or rz)
-s string Use string as the line number separator
-v number Set the starting line number to number

Troubleshooting Tips

If you encounter an error when using nl, it may be due to incorrect syntax or incorrect use of options. Double-check the command and options to ensure they are entered correctly.

If you are having trouble getting the desired output, try experimenting with different options to see how they affect the line numbering.

Notes

It is important to note that nl does not modify the original file. Instead, it outputs the result with line numbers added to the terminal. If you wish to save the output to a file, you can use the > operator to redirect the output to a file:

nl filename > output.txt