Display only the n'th match of grep

Andrew Tsay picture Andrew Tsay · Feb 28, 2013 · Viewed 65.9k times · Source
onefish
onechicken
twofish
twochicken
twocows
threechicken

What if I want to grep for lines containing "two", but I only want the 2nd match. So I want the result "twochicken".

Answer

Kent picture Kent · Feb 28, 2013

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