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: 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.
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.
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.
-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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With