UNIX & GNU/Linux - awk - Using NR to display line numbers before each line from a file

We have a file with customers inside.

We would like to display all the file with line numbers before each line.

Let's see this in this awk tutorial.

Explanation

The NR variable is a awk builtin variable, to display the number (a sort of static variable).
The $0 represents every column separated by default by the space character.
The coma between will create a space character for our output.

All the code inside the dev statement, will be executed until there is no line.

For compiling, we have to add the -f flag to tell to awk that our script need a file.

Code

customers.txt

Georges William 12-2-1967 M 1895602
John Maynard 7-4-1944 W 981502
Wolfgang Amadeus 3-11-1938 M 64158674102
Ludwig SCHMILL 11-28-1957 M 5648510
Antonio VAVILDA 5-16-1937 M
Hugues Ofrette 8-11-1958 M 4515660
Dagobert ELOY 7-14-1905 M 0225415487

Akio Shamiwara 1-2-1965 n 4
Antonio SZWPRESWKY 19-5-8937 M 0298358745

bp1.awk

#!/bin/awk

# Begin
BEGIN {}

# Dev
{
    print NR, $0
}

# End
END {}

Executing

awk -f bp1.awk customers.txt

Output

1 Georges William 12-2-1967 M 1895602
2 John Maynard 7-4-1944 W 981502
3 Wolfgang Amadeus 3-11-1938 M 64158674102
4 Ludwig SCHMILL 11-28-1957 M 5648510
5 Antonio VAVILDA 5-16-1937 M
6 Hugues Ofrette 8-11-1958 M 4515660
7 Dagobert ELOY 7-14-1905 M 0225415487
8 
9 Akio Shamiwara 1-2-1965 n 4
10 Antonio SZWPRESWKY 19-5-8937 M 0298358745

Finally

Well done, you've made it. smiley

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.