42

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
One Two Three
  • 22,327
  • 24
  • 73
  • 114

3 Answers3

61

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
Tim Pote
  • 27,191
  • 6
  • 63
  • 65
3

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].

mrketchup
  • 118
  • 6
2

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX
mawia
  • 9,169
  • 14
  • 48
  • 57