The NR variable

awk has a built-in variable called NR. It stores the record number. Initially, the value stored in NR is 1. Then, it will be incremented by one for each new record.

Take, for example, the following command:

    $ cat people.txt
  

The output will be:

    Bill Thomas  8000  08/9/1968
    Fred Martin  6500  22/7/1982
    Julie Moore  4500  25/2/1978
    Marie Jones  6000  05/8/1972
    Tom Walker   7000  14/1/1977
    $ awk '{print NR, $0}'  people.txt
    The output will be:
    1 Bill Thomas  8000  08/9/1968
    2 Fred Martin  6500  22/7/1982
    3 Julie Moore  4500  25/2/1978
    4 Marie Jones  6000  05/8/1972
    5 Tom Walker   7000  14/1/1977
  

This has printed every record, such as $0 with a record number, which is stored in NR. That is why we see 1, 2, 3, and so on before every line of output. ...

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.