1

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

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
kate
  • 291
  • 3
  • 15

7 Answers7

3

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
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1
 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.

Kent
  • 189,393
  • 32
  • 233
  • 301
1
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

Community
  • 1
  • 1
1

Using sed

sed '/str/{x;//q;x;h}' file

...
str
...
str
123
  • 10,778
  • 2
  • 22
  • 45
  • @kate No problem, if you don't understand anything just ask :) – 123 Jan 12 '16 at 14:18
  • 1
    This will repeat the line with the first `str` as the last line if a second `str` exists. Perhaps `sed '/str/{x;//{x;q};x;h}' file` is safer? – potong Jan 12 '16 at 19:42
  • @potong Yes i (possibly wrongly) assumed that str was the entire line. That would be safer though. – 123 Jan 13 '16 at 08:04
0

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.

Guru
  • 16,456
  • 2
  • 33
  • 46
0

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
steviethecat
  • 870
  • 9
  • 14
0

If Perl is an option:

perl -pe '$m++ if /str/; exit if $m==2' file

Counts the matches. Exits if matches == 2.

Chris Koknat
  • 3,305
  • 2
  • 29
  • 30