
Let's say there is a file file with a few lines of text.
Hello world
How are you today
I hope all is well
The NL command without any options will number each line in the file. This is very helpful when using the join command, as the JOIN command requires columns with identical values.
~]# nl file1
1 Hello world
2 How are you today
3 I hope all is well
Where does line end?
How does the NL command know where one line ends and the next begins? Using the cat command with the -A option, we can detect the end of a line with the $ metacharacter. The NL command uses the $ metacharacter to detect each line in the file.
~]# cat -A file1
Hello world$
How are you today$
I hope all is well$
5 leading zeros
By default, the NL commands places 5 non-visible leading zeros before each line of text. The 5 leading zero's can be viewed using the -nrz (format right justified & show leading zeros).
~]# nl -nrz file1
000001 Hello world
000002 How are you today
000003 I hope all is well
The NL command with the -nrl (format right justified & do not show leading zeros) is the equivelant of the NL command with no options.
~]# nl -nrl file1
1 Hello world
2 How are you today
3 I hope all is well
Left justify
The -nln (format left justified) can be used to remove the 5 leading zeros.
~]# nl -nln file1
1 Hello world
2 How are you today
3 I hope all is well
The same can be accomplished using the -w1 (width 1) option.
~]# nl -w1 file1
1 Hello world
2 How are you today
3 I hope all is well
3 spaces
By default, there are also 3 spaces between the number and the start of the line. This can be viewed using the -sTAB (string tab) option.
~]# nl -sTAB file1
1TABHello world
2TABHow are you today
3TABI hope all is well
Some other string can be used in place of TAB, such as a single period.
~]# nl -s. file1
1.Hello world
2.How are you today
3.I hope all is well
Combining -w1 and -s. produces a pretty nice STDOUT.
~]# nl -w1 -s. file1
1.Hello world
2.How are you today
3.I hope all is well
Start at some number other than 1
By default, the NL command uses the -v1 option, which starts the number at 1. The can be modified using the -v option.
~]# nl -v7 file1
7 Hello world
8 How are you today
9 I hope all is well
Dealing with empty lines
Let's say there are spaces in file1.
~]# cat -A file1
Hello world$
$
How are you today$
$
I hope all is well$
The NL command with no options will not number empty lines.
~]# nl file1
1 Hello world
2 How are you today
3 I hope all is well
The NL command with the -bt (body number only non-empty lines) produces the same result.
~]# nl -bt file1
1 Hello world
2 How are you today
3 I hope all is well
To number empty spaces the -ba (body numbering all) option can be used.
~]# nl -ba file1
1 Hello world
2
3 How are you today
4
5 I hope all is well
Did you find this article helpful?
If so, consider buying me a coffee over at