Linux/Unix: grep Command Show Line Numbers While Displaying Output

I am a new Unix (OS X to be specific) user. How do I show line number while displaying the output using the grep command on Linux or Unix-like operating systems? How can I show matched lines together with their line numbers on my Terminal?

grep command is used to search files. The basic syntax is:

Tutorial details
Difficulty level Easy
Root privileges No
Requirements grep+Terminal
Est. reading time 1m
grep 'word' file
grep 'word1 word2' file1 file2
grep [option] 'word1 word2' file1 file2

The -n or --line-number grep option

You can pass either -n or --line-number option to the grep command to prefix each line of output with the line number within its input file. The syntax is:

grep -n 'patten' file
grep -n 'patten' file1 file2
grep -n [options] 'pattens' file

In this example search for a patter/word called ‘/dev’ in /etc/fstab file and display line number while displaying the output on screen:

grep -n '/dev' /etc/fstab

Sample outputs:

6:# Accessible filesystems, by reference, are maintained under '/dev/disk'
13:tmpfs                   /dev/shm                tmpfs   defaults        0 0
14:devpts                  /dev/pts                devpts  gid=5,mode=620  0 0

For better result I suggest you pass the –color option to gnu/grep command:

grep -n --color '/dev' /etc/fstab

Sample outputs:

Fig.01: Displaying line number while doing grep on a file

Suggested readings

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum