grep
is not designed to search patterns over multiple lines. There are other tools better suited for this task: awk
and sed
.
Since you are using variables to hold the patterns things can get tricky. Please try first with hardcoded patterns. If you got that right then try to replace the hardcoded patterns with variables.
Using awk
:
awk '/'"$Var1"'/,/'"$Var2"'/' file.txt
The same command with hardcoded patterns to explain the concept:
awk '/pattern1/,/pattern2/' file.txt
Explanation:
/pattern1/,/pattern2/
is a range. the range begins at the line matching pattern1
and ends at the line matching pattern2
.
- by default
awk
only prints lines that are in the range.
Learn more about awk
: http://www.catonmat.net/blog/awk-one-liners-explained-part-one/
Using sed
:
sed -n '/'"$Var1"'/,/'"$Var2"'/ p' file.txt
The same command with hardcoded patterns to explain the concept:
sed -n '/pattern1/,/pattern2/ p' file.txt
Explanation:
-n
makes sed to print lines only if told.
/pattern1/,/pattern2/
is a range. the range begins at the line matching pattern1
and ends at the line matching pattern2
. for every line in that range the following commands are executed.
- the
p
at the end tells sed
to print lines.
Learn more about sed
: http://www.catonmat.net/blog/sed-one-liners-explained-part-one/
If you really have to use grep
then you can use -P
to tell grep
to use the perl regular expression engine. The man page has this to say about that feature:
Interpret the pattern as a Perl-compatible regular expression (PCRE). This is highly experimental and grep -P may warn of unimplemented features.
sed
for that, How can I use variables when doing a sed? more specifically How to ensure that string interpolated intosed
substitution escapes all metachars? – don_crissti Dec 09 '16 at 17:00