Use the bash &&
operator ("AND" )
The bash operator &&
joins two commands. It runs the second command only if the first command produces an exit status of 0. The advantage of using &&
to conditionally chain commands is that it is a quick and easy-to-remember method for producing shell scripts, compared to the complex syntax that can be required for accomplishing a task in one pass of a single command.
Since the exit status of grep
can be 0 (when it finds a matching pattern) or 1 (when it doesn't find a match), you can use grep
and &&
to check a file for a pattern before printing any lines:
file="file.txt" ; grep -q -E '^\*{5} END \*{5}$' "${file}" && sed -n -r '/^\*{5} BEGIN \*{5}$/,/^\*{5} END \*{5}$/p' "${file}"
CAUTION: This example assumes that the BEGIN pattern will occur before the END pattern. This may be a safe assumption, since the question does not show examples where END occurs before BEGIN. If a robust method for dealing with complications is not necessary, the developer's time is better spent on other tasks.
The same code, formatted for easier reading:
file="file.txt"
grep -q -E '^\*{5} END \*{5}$' "${file}" && \
sed -n -r '/^\*{5} BEGIN \*{5}$/,/^\*{5} END \*{5}$/p' "${file}"
In this example, -q
tells grep
to print no output; this does not affect the exit codes. The -E
tells grep
that we are using extended regular expressions (in this case, to shorten \*\*\*\*\*
to \*{5}
).
If grep
detects the END pattern, then the sed
command runs. The -r
does for sed
what -E
does for grep
. Using -n
with p
tells sed
to print from the line containing the BEGIN pattern to the line containing the END pattern, as you tried in the question.
If the asterisks and spaces in the BEGIN and END patterns don't matter, the code is shorter:
file="file.txt" ; grep -q 'END' "${file}" && sed -n '/BEGIN/,/END/p' "${file}"
The same shorter example, formatted for easier reading:
file="file.txt"
grep -q 'END' "${file}" && \
sed -n '/BEGIN/,/END/p' "${file}"
sed
( or at least not easily)sed
is Turing-complete so it can be done in sed, though that doesn't mean it's always a good idea. In this case, though, it's not too bad.