1

This question already has an answer here:

Several questions are similar to this one, but I have not found a solution that works when I want to search for a pattern over several lines. The following

sed -n '/First string/,/Second string/ p' my.file

will print all occurrences of the matched pattern, but I would like only the first occurrence. I am using GNU sed.

marked as duplicate by don_crissti, terdon May 5 '17 at 12:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • post your input text and expected output – RomanPerekhrest May 5 '17 at 12:19
  • First occurrence or first line? – schaiba May 5 '17 at 12:23
6

Use q to explicitly quit when the end pattern is reached.

In GNU sed:

$ cat foo
foo
START
bar
END
blah
START another

$ sed -n '/START/,/END/p; /END/q' foo
START
bar
END

awk would maybe make it easier to not repeat the end pattern:

$ awk '/START/{p=1} p; /END/{exit}' foo
START
bar
END
1

If it's first occurrence you want, perhaps awk is better suited for this : awk 'NR==1,/original/{sub(/original/, "replacement")} 1' file . Taken from here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.