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

by on November 20, 2011 · 0 comments· LAST UPDATED November 20, 2013

in , ,

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
DifficultyEasy (rss)
Root privilegesNo
Estimated completion time1m
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

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

Suggested readings
Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?

{ 0 comments… add one now }

Leave a Comment

Tagged as: ,

Previous Faq:

Next Faq: