Display only the n'th match of grep

try this:

awk '/two/{i++}i==2' file

with your data:

kent$  echo "onefish
onechicken
twofish
twochicken
twocows
threechicken"|awk '/two/{i++}i==2'
twochicken

note: if your file is huge, do this:

awk '/two/{i++}i==2{print; exit}' file

grep -m2 "two" in-file.txt | tail -n1

Stop after the second match, then take the second line printed.


grep and sed can be used to filter the line number.

testfile:

onefish
onechicken
twofish
twochicken
threechicken
twocows

Getting the desired line:

grep "two" testfile | sed -n 2p
prints "twochicken"

grep "two" testfile | sed -n 1p
prints "twofish"