7

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.

Yoda
  • 293

2 Answers2

14

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
ilkkachu
  • 138,973
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.

schaiba
  • 7,631