42
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".

Anders R. Bystrup
  • 15,324
  • 10
  • 61
  • 54
Andrew Tsay
  • 1,703
  • 6
  • 21
  • 32

6 Answers6

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

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

John Zwinck
  • 223,042
  • 33
  • 293
  • 407
33

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
Kent
  • 181,427
  • 30
  • 222
  • 283
9

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"
Joy
  • 187
  • 2
  • 7
2

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.

Louis
  • 566
  • 5
  • 9
1

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.

anishsane
  • 19,124
  • 5
  • 38
  • 71
1

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.

Alex
  • 171
  • 2
  • 4