nl

2024-08-21

Basic Line Numbering

The simplest use of nl is to add line numbers to a file. Let’s say you have a file named my_file.txt with the following content:

This is line one.
This is line two.
This is line three.

To add line numbers, simply pipe the file’s content to nl:

cat my_file.txt | nl

This will output:

     1  This is line one.
     2  This is line two.
     3  This is line three.

Notice the default behavior: line numbers are left-aligned, separated by a tab from the text, and begin at 1.

Customizing Line Numbers

nl offers a wealth of options for customizing the numbering. Let’s look at some key options:

cat my_file.txt | nl -s ':'

Output:

1:This is line one.
2:This is line two.
3:This is line three.
cat my_file.txt | nl -w 5

Output:

00001   This is line one.
00002   This is line two.
00003   This is line three.
cat my_file.txt | nl -n rz -w 3

Output:

001 This is line one.
002 This is line two.
003 This is line three.
cat my_file.txt | nl -b t

This will only number lines with text, ignoring blank lines if any were present in my_file.txt.

cat my_file.txt | nl -v 10

Output:

    10  This is line one.
    11  This is line two.
    12  This is line three.

Numbering Specific Sections of a File

nl can also be used in conjunction with other commands like sed or awk to number specific sections of a file. For example, to only number lines containing the word “line”:

sed -n '/line/p' my_file.txt | nl

This uses sed to filter lines containing “line” and then pipes the output to nl for numbering.

In-Place Numbering

While the examples above show using nl with pipes, it’s also possible to number a file in-place using output redirection:

nl -n ln -w 3 -s ' - ' my_file.txt > temp_file.txt && mv temp_file.txt my_file.txt

This will overwrite the original my_file.txt. Remember to always back up your files before performing in-place modifications.

These examples demonstrate the flexibility and power of the nl command. By combining nl with other text processing tools, you can achieve complex line numbering tailored to your specific needs.