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".
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".
grep -m2 "two" in-file.txt | tail -n1
Stop after the second match, then take the second line printed.
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 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"
To use grep command for the n_th match, we can use the combination of head and tail commands like this:
grep two file.txt | head -n1 | tail -1
where n1 is the n_th match we need.
If the word (here word==two) repeats multiple time in a single line, & you want to print that line, use below:
word=two
n=2
line=`grep -m$n $word -o -n MyFile | sed -n $n's/:.*//p'`
awk 'FNR=='$line'{print; exit}' MyFile
e.g. For below input:
onefish
onechicken
twotwofish
twochicken
twocows
threechicken
it will print twotwofish, instead of twochicken.
This may not be what user1787038 wants, but added to answer my own comment.
It should be noted that if the threechicken and twocows lines were swapped, aka:
onefish
onechicken
twofish
twochicken
threechicken
twocows
then Kent's first response (awk '/two/{i++}i==2' file) would yield the output:
twochicken
threechicken
because it takes another occurrence of the match to increment the counter. His last response: awk '/two/{i++}i==2{print; exit}' file avoids this issue.
The question is about grep so let's stick with it:
$ cat testfile
onefish
onechicken
twofish
twochicken
twocows
threechicken
$ grep two testfile | while read line; do
((n++))
((n==2)) && { echo "$line"; break; }
done
twochicken