grep is a popular tool in order to search and find a given term in files. grep can search multiple files at the same time and match using regular expressions etc. While searching files the matched lines can be printed to the screen with the grep command. In this tutorial, we will examine different ways to print line numbers of the matched lines with the grep command.
Print Line Number of the Matched Line
-n option is used to print the line number of the all matched lines. We will also provide the term want to search and match. In the following example we will search the
/etc/passwd file for the term
ismail and print the line number of the matched lines.
$ grep -n "a" /etc/passwd
We can see that the line numbers are printed at the start of the lines of the output. Then double colon is used and then the line content is printed. Also the matched part of the lines are printed with color red.
Print Line Number For Complete Matched Lines
We can also match a complete word not a part of the word and then print these lines numbers. We will use the
-v option where the -v option is used for a complete match.
$ grep -n -v "a" /etc/passwd
Print Line Number For Recursive Search
We can also search multiple files and directories content for a match and then print these results line numbers. We will use the
-r option for recursive search. In the following example we will search term
ismail under the
/etc recursively in all files and folders. The results will contain the file name, line number and line content like below.
Print Only Line Number Not The Line
By default the grep command will print the line number with the matched line and file name for recursive search. You may need to list or get the only line number of the matched lines. Some helpful command can be used to print only line numbers. In the following example we will use the
cut command by redirecting the grep output.
$ grep -n -v "a" /etc/passwd | cut -d : -f 1 3 4 5 12 18 20 23 26 27 32 46 48