๐ŸŽ New User? Get 20% off your first purchase with code NEWUSER20 ยท โšก Instant download ยท ๐Ÿ”’ Secure checkout Register Now โ†’
Menu

Categories

๐Ÿ’ก Text Processing August 27, 2026 3

Linux Command: nl

Number lines of files

Terminal โ€” Text Processing
Command
$ nl -ba script.sh
Output
1 #!/bin/bash 2 3 echo "Hello"

The nl command numbers lines of files, providing more formatting control than cat -n. It supports different numbering styles, formats, and can selectively number only non-empty lines or lines matching specific patterns. nl divides input into logical sections (header, body, footer) and can apply different numbering rules to each section. This makes it useful for formatting source code listings, reports, and documents. While cat -n provides basic line numbering, nl offers customizable number format, width, separator string, and selective numbering โ€” making it the better choice for producing formatted, professional output.

Syntax

nl [OPTION]... [FILE]...

Key Options

  • -b a โ€” Number all lines including blank lines
  • -b t โ€” Number only non-empty lines (default)
  • -b p โ€” Number only lines matching a regex pattern
  • -n ln โ€” Left-justified line numbers
  • -n rz โ€” Right-justified with leading zeros
  • -w โ€” Set width of line number field

Examples

Number all lines

nl -ba script.sh

Output: 1 #!/bin/bash 2 3 echo "Hello"

Number with leading zeros

nl -nrz -w4 data.txt

Output: 0001 First line 0002 Second line

Number only non-empty lines

nl config.conf

Pro Tips

  • nl -s'. ' -w2 creates numbered lists like 1. First item. Use in scripts to format output.
  • cat -n is simpler but numbers all lines with fixed format. nl offers customizable numbering style, width, separator, and selective numbering.
  • By default, nl does not number blank lines. Use -ba if you need all lines numbered (like cat -n behavior).

Learn more: Full nl reference โ†’

Share this tip