Text and processing
The nl command
Numbers the lines of a file. It is like cat -n, but with control over the format, and it leaves empty lines unnumbered, which is the default.
Most useful options
-b <estilo>Which lines to number: a (all), t (non-empty, default), n (none) or pREGEX (those matching the expression)-n <formato>Number format: ln (left), rn (right, default) or rz (right, with leading zeros)-w <n>Width of the number in columns. Default is 6-s <texto>Text between the number and the line. Default is a tab-v <n>Number of the first line. Default is 1-i <n>Increment between one number and the next. Default is 1Copy-ready examples
$ nl notas.txtnumbers the lines with text. Empty ones stay unnumbered.Example output
1 hola
2 adios$ nl -ba script.shnumbers the empty lines too, to cite a specific line of a script.$ nl -b pERROR registro.lognumbers only the lines that contain the word ERROR.$ nl -nrz -w3 lista.txtnumbers with leading zeros: 001, 002, 003...Example output
001 hola 002 adios
$ nl -v10 -i10 -w3 -s': ' capitulo.mdstarts at 10 and counts up by 10, with a colon as separator.Example output
10: hola 20: adios
You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| nl: nofile: No such file or directory | The file does not exist or is misspelled. | List the folder with ls and type the exact name. |
| nl: invalid body numbering style: 'x' | The -b style is not valid. The only ones are a, t, n and pREGEX. | Use -b a to number all lines or -b t for non-empty ones. |
Typical mistakes
- By default it does not number empty lines: if you want them counted, use -ba.
- nl does not change the file: it prints the numbering to the output. To keep it, redirect to another file with >.
Differences from similar commands
FAQ
What is the difference between nl and cat -n?
cat -n numbers every line and offers no formatting. nl skips empty lines by default and lets you change width, separator, zero padding and regular expressions.
How do I number with leading zeros?
With -nrz: nl -nrz -w3 file produces 001, 002, 003. -w sets how many digits the number has.
Can I number only the lines that match something?
Yes: -b pREGEX numbers only the lines that match the basic regular expression. For example, -b p^ERROR numbers only the ones starting with ERROR.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course