AWK: Use of NR Builtin: How to print record number using NR ?

In this article, we will look at AWK NR Bultin to print the record number.

What is NR bultin ?
In AWK, NR refers to “Number of Record” and prints the number of record which is currently being read by AWK.

Lets see few examples to understand the NR function.

Example 1: Print /etc/passwd file with numbers in front.
1. root—-
2. gdm—
3.—, etc

Lets see the above example on bash shell.

[root@nglinux ~]# cat /etc/passwd | awk '{print NR"."$0}'
1.root:x:0:0:root:/root:/bin/bash
2.bin:x:1:1:bin:/bin:/sbin/nologin
3.daemon:x:2:2:daemon:/sbin:/sbin/nologin
4.adm:x:3:4:adm:/var/adm:/sbin/nologin
5.lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
6.sync:x:5:0:sync:/sbin:/bin/sync
7.shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
8.halt:x:7:0:halt:/sbin:/sbin/halt
9.mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
10.uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
11.operator:x:11:0:operator:/root:/sbin/nologin
12.games:x:12:100:games:/usr/games:/sbin/nologin
13.gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
14.ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
15.nobody:x:99:99:Nobody:/:/sbin/nologin
16.dbus:x:81:81:System message bus:/:/sbin/nologin
17.usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
18.rtkit:x:499:497:RealtimeKit:/proc:/sbin/nologin
19.avahi-autoipd:x:170:170:Avahi IPv4LL Stack:/var/lib/avahi-autoipd:/sbin/nologin
20.vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
21.pulse:x:498:496:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
22.haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
23.ntp:x:38:38::/etc/ntp:/sbin/nologin
24.apache:x:48:48:Apache:/var/www:/sbin/nologin
25.saslauth:x:497:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin
26.postfix:x:89:89::/var/spool/postfix:/sbin/nologin
27.abrt:x:173:173::/etc/abrt:/sbin/nologin
28.gdm:x:42:42::/var/lib/gdm:/sbin/nologin
29.sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
30.tcpdump:x:72:72::/:/sbin/nologin
31.mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
32.hsqldb:x:96:96::/var/lib/hsqldb:/sbin/nologin
33.nglinux:x:500:500:NGE Linux User:/home/nglinux:/bin/bash
34.ricci:x:140:140:ricci daemon user:/var/lib/ricci:/sbin/nologin
35.rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
36.rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
37.nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
38.luci:x:141:141:luci high availability management application:/var/lib/luci:/sbin/nologin
39.saket:x:501:501::/home/saket:/bin/bash
[root@nglinux ~]# 

Example 2: To print number of fields in /etc/passwd file using awk NR field.

### Usually, we use wc command.
[root@nglinux ~]# cat /etc/passwd | awk '{print NR}' | tail -1
39

### Using AWK
[root@nglinux ~]# cat passwd_backup | awk '{print NR}' | tail -1
39
[root@nglinux ~]# 

Leave a Reply

Your email address will not be published.