I have a simple question. I have a file containing:
more random text
*foo*
there
is
random
text
here
*foo*
foo
even
more
random
text
here
foo
more random text
With sed:
$ sed -n '/foo/{:a;n;/foo/q;p;ba}' infile
there
is
random
text
here
Explained:
/foo/ { # If we match "foo"
:a # Label to branch to
n # Discard current line, read next line (does not print because of -n)
/foo/q # If we match the closing "foo", then quit
p # Print line (is a line between two "foo"s)
ba # Branch to :a
}
Some seds complain about braces in one-liners; in those cases, this should work:
sed -n '/foo/ {
:a
n
/foo/q
p
ba
}' infile
Since checking for "foo" (using /foo/
) is relatively expensive, the following avoids that check and will work with all awk
s worthy of the name:
awk 'c==2 {next} /foo/{++c;next} c==1' file
$ awk '/foo/{++c;next} c==1' file
there
is
random
text
here
$ awk '/foo/{++c;next} c==3' file
even
more
random
text
here
or with GNU awk for multi-char RS you COULD do:
$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==2' file
there
is
random
text
here
$ awk -v RS='(^|\n)[^\n]*foo[^\n]*(\n|$)' 'NR==4' file
even
more
random
text
here
See https://stackoverflow.com/a/17914105/1745001 for other ways of printing after a condition is true.