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.
grep Line Number Syntax
The grep command line number option has the following syntax.
grep -n PATTERN FILE
- PATTERN is the pattern or text or regular expression we want to match. This is required.
- FILE is the file name or path which is searched for the PATTERN. This is required.
- -n option is used to print the line number. Alternatively the –line-number option can be used which is the long form of the -n option.
Print Line Number of the Matched Lines
-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 options 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 commands 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