Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display only the n'th match of grep

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

like image 631
Andrew Tsay Avatar asked Feb 28 '13 12:02

Andrew Tsay


People also ask

How do I print only a grep matched string?

Grep: Print only the words of the line that matched the regular expression, one per line. We used the following parameters on our command: -h, –no-filename : Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

How do you grep the nth line after a match?

To get the n-th line after each match, we can first use grep -An to find each block with n+1 lines. Next, instead of piping it to grep -v, we pipe it to a command that can print every (n+1)-th line. As the output above shows, we've got the 3rd line after each “Performance: BAD” line.

How do you grep for a word and display only the word?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

What is N in grep?

-n : Display the matched lines and their line numbers. -v : This prints out all the lines that do not matches the pattern -e exp : Specifies expression with this option.


2 Answers

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

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

like image 68
John Zwinck Avatar answered Oct 02 '22 05:10

John Zwinck


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 
like image 23
Kent Avatar answered Oct 02 '22 05:10

Kent