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:

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

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts