My file:
...
str
...
str
...
I use:
sed '/str/q' myfile
This prints:
...
str
But I need:
...
str
...
str
How can I get result above? (...
are other strings.)
My file:
...
str
...
str
...
I use:
sed '/str/q' myfile
This prints:
...
str
But I need:
...
str
...
str
How can I get result above? (...
are other strings.)
Depending on the requirements you haven't stated in your question, this MAY be what you want:
$ awk '1; /str/&&c++{exit}' file
...
str
...
str
awk '/str/{++i}7;i==2{exit}' file
should works for your requirement.
It record the match count in variable i
, when the count ==2
exit processing.
sed '/str/{:second n; /str/q; b second}' myfile
When SED finds the first 'str', starts a loop until the next one is found.
More details here: SED loop match
Using sed
sed '/str/{x;//q;x;h}' file
...
str
...
str
One way:
awk '/str/ && f{print;exit}/str/{f=1}1' f=0 file
When /str/ is encountered first time, set a variable to 1 and keep printing. Next time, when encountered, print the line and stop the execution.
Another way, count the matches and exit on the second match. Print other lines.
awk 'BEGIN {m=0}; {print}; /str/ {m++; if ( m == 2 ) { exit; } }' file
If Perl is an option:
perl -pe '$m++ if /str/; exit if $m==2' file
Counts the matches. Exits if matches == 2.