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

grep, sed, unix

Solution

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

Problem

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?

Original source