Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the line number where a specific word appears with "grep" [closed]

Tags:

grep

unix

sed

Is grep capable of providing the line number on which the specified word appears?

Also, is possible to use grep to search for a word starting from some certain line downward?

like image 921
One Two Three Avatar asked May 14 '12 19:05

One Two Three


People also ask

How do I search for a specific word in a grep file in Linux?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do you grep a line after a match?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.

Which grep command finds all the lines that have only the word Linux in file txt?

If you want to search for fixed strings only, use grep -F 'pattern' file .

How do I go to a specific line number in vi editor?

If you're already in vi, you can use the goto command. To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file.


2 Answers

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file 

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/' 

Or you could simply use sed:

sed -n '/regex/=' file 

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file 
like image 195
Tim Pote Avatar answered Oct 07 '22 15:10

Tim Pote


You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/ 

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

like image 40
mrketchup Avatar answered Oct 07 '22 15:10

mrketchup