Print Line Numbers In AWK

awk is a popular Linux and Unix to work with text files and command output by manipulating them. While using the awk command it can be useful to add line numbers. This can be especially beneficial for the source codes or configuration files. In this tutorial, we examine how to print line numbers in awk in a different way.

Print Line Numbers

The print command can be used for the awk in order to print line numbers. In the following example, we start printing numbers from 0. The i variable is used to store line numbers and ++ operators have used the increase the i variable in every line. In the following example, we print line numbers for the file named phpinfo.php .

$ awk '{print i++ "," $0}' phpinfo.php
Print Line Numbers

Print Line Numbers Starting From 1

Alternatively, we can start the line numbers for the awk command from 1. The variable i is set as 1 and incremented in every line.

$ awk '{print i++ "," $1}' phpinfo.php

We can also use the NR-1 statement in order to print line numbers. The starting number like 0 or 1 is specified with the NR like below.

$ awk '{print NR-1 "," $0}' phpinfo.php

Print Line Numbers with grep

Alternatively to the awk command the grep command can be used to print lines.

$ grep -n 'bla' phpinfo.php

Print Line Numbers with perl

The perl command is another popular alternative to the awk command to print line numbers.

$ perl -ne 'print $.,":",$_ if /bla/' phpinfo.php

Leave a Comment