How to Use awk to Print Out Line Numbers


Often you may want to use awk to print out line numbers for each line in a file.

You can use the following basic syntax to do so:

awk '{print NR ":" $0}' cities.txt

This particular example will print each line in the file named cities.txt with the line number printed in front of each line with a colon.

Note that the NR command stands for “total record number” and uses 1 as the default starting line number.

If you would like the first line number to be 0 then you can use the following syntax instead:

awk '{print NR-1 ":" $0}' cities.txt

The following example shows how to use each of these methods in practice.

Example: How to Use awk to Print Out Line Numbers

Suppose we have a file named cities.txt that contains the names of various U.S. cities:

Suppose that we would like to print the text from the file with the line number at the beginning of each line.

We can use the following syntax to do so:

awk '{print NR ":" $0}' cities.txt

The following screenshot shows how to use this syntax in practice:

awk print line numbers in file

Notice that this returns each line from the file with the line number and a colon printed before it.

Note that we could also use the following syntax to start the line numbers at 0 instead of 1:

awk '{print NR-1 ":" $0}' cities.txt

The following screenshot shows how to use this syntax in practice:

awk print line numbers starting at zero

This returns each line from the file with the line number and a colon printed before it, using 0 as the first line number.

Note: Feel free to replace the colon ( : ) with a different character if you would like to use a different character to separate the line number from the content.

Related Tutorials

The following tutorials explain how to perform other common tasks in awk:

How to Use awk to Print All Columns After Specific Number
How to Use awk to Print Rows Where Column Equals Value
How to Use awk to Print Last Line of a File
How to Use awk to Print a Range of Columns

Leave a Reply