Home > Text Processing & Search > nl

nl: Numbering Lines of Files

The nl command numbers the lines of files and writes the result to standard output. It allows control over whether blank lines are included, the format of the numbers, and the separator, making it useful for log file analysis or code reviews.

Overview

nl numbers the lines of standard input or specified files and writes them to standard output. It is primarily used to enhance the readability of text files or to reference specific lines.

Key Features

  • Numbering lines of files
  • Controlling numbering of blank lines
  • Customizing number format and separator
  • Setting numbering for header/body/footer sections

Key Options

The main options for the nl command are used to control the line numbering method, format, and separator.

Line Numbering Methods

Number Format and Separator

Generated command:

Try combining the commands.

Description:

`nl` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Learn how to effectively number lines of files through various usage examples of the nl command.

Basic Line Numbering

echo -e 'Line 1\n\nLine 3' | nl

Numbers all lines of a file (default behavior).

Numbering Non-Blank Lines Only

echo -e 'Line 1\n\nLine 3' | nl -b t

Numbers only lines with content, skipping blank lines.

Using a Custom Separator

echo -e 'First line\nSecond line' | nl -s ' -> '

Uses a specific string as a separator between the line number and the text.

Specifying Number Width and Format

echo -e 'Line 1\nLine 10\nLine 100' | nl -w 3 -n rz

Sets the minimum width for line numbers to 3 and right-justifies with zero padding.

Numbering Lines Matching a Regular Expression

echo -e 'Line 1\nAnother line\nLine 2' | nl -b p'^Line'

Numbers only lines that match a specific regular expression (`^Line`).

Tips & Notes

Tips and points to consider for more effective use of the nl command.

Usage Tips

  • You can pipe (`|`) nl with other text processing commands (e.g., `grep`, `sed`, `awk`) to number only specific lines based on conditions or perform further operations on numbered files.
  • By default, `nl` uses tabs as separators, so the spacing between line numbers and text may appear differently depending on your terminal settings. It's recommended to use an explicit separator with the `-s` option.
  • When using the `-b pREGEX` option, the regular expression follows Basic Regular Expression (BRE) syntax. For Extended Regular Expressions (ERE), consider using `grep -n` or `awk` instead of `nl`.

Same category commands