nl - macOS


Overview

nl (number lines) adds line numbers to a text file. It is commonly used for tasks like line-by-line code review, debugging, and generating test cases with line number references.

Syntax

nl [options] [file1 ...]
nl [options] -

Options/Flags

  • -b: Specifies the style of line numbering. Valid options are:
    • a: Number all lines
    • t: Number only non-empty lines
    • n: Number only lines containing a non-whitespace character
  • -e: Don’t print the line number for lines beginning with a whitespace character
  • -f: Specify the starting line number (default: 1)
  • -i: Increment line numbers by a specified value (default: 1)
  • -l: Left-justify the line numbers instead of right-justifying them
  • -s: Specifies the separator between line numbers and text. Default is a space.
  • -v: Print the version number
  • -w: Specify the width of the line number field (default: 6)
  • -: Read from standard input instead of a file

Examples

Number all lines of a text file:

nl my_file.txt

Number only non-empty lines:

nl -bt my_file.txt

Left-justify the line numbers:

nl -l my_file.txt

Specify a custom increment:

nl -i 5 my_file.txt

Use a custom separator:

nl -s ":" my_file.txt

Common Issues

Negative line numbers: Ensure that the starting line number (-f) and increment (-i) are non-negative values.

Malformed input: Verify that the input file is valid and contains only text characters.

Integration

Combining with grep: Search for specific line patterns with line numbers:

nl -ba my_file.txt | grep "pattern"

Generating numbered test cases: Create a numbered list of test cases with line numbers for automated testing:

nl my_test_cases.txt | sed 's/^/Test Case /'
  • cat: Concatenate and print files
  • more: Display a file page by page
  • wc: Count lines, words, and characters in a file