Networking | Programming | Security | Linux | Computer Science | About

Adding line numbers to a file using nl

The nl utility is useful for displaying line numbers in a file. This utility displays a file with line numbers added to each line. The utility breaks its input into logical pages. By default, the line number is reset to 1 at the top of each logical page. It treats all of the input files as a single document and does not reset line numbers or logical pages between files.

A logical page consists of three sections: header, body, and footer. Any of the sec- tions can be empty. Each can be numbered in a different style from the others. An empty line of output replaces a section separator. Any text that comes before the first section separator string in the input file is considered to be part of a body sec- tion, so the nl utility treats a file that contains no section delimiters as a single body section.

Several options can be used to customize the output gained using this utility, and several of those options are shown below.

-a Numbers all lines
-t Numbers only nonempty lines
-n Does not number lines (the default for headers and footers)
-i NUMBER Increments line numbers by NUMBER with the default value of one.
-p Does not reset line numbers at the start of each logical page.
-s STRING Adds the STRING after the added line number.
-v NUMBER Sets the initial line number on each logical page to NUMBER.
-w NUMBER Specifies the NUMBER of character spaces to reserve for line numbers. The default value is six.

Below is an example of the use the nl utility. In this example the nicks file is printed with a number corresponding to each line.

# nl nicks
1 Bammage
2 Rexmortis
3 Jackyl
4 Dragonstr
5 Alchemist
6 Just_joe
7 Johan
8 Sting
9 Dave
10 Thomas
11 Netchick
12 Netjunkie
13 Pri
14 Zaphod
15 Lordram

Published on Fri 07 May 2004 by Laura Edson in Linux with tag(s): nl line numbers