3

I'm trying to grab a specific range of lines from a text file using grep; the line range needs to be identified by two variables. so far, I've been trying to do it using the wildcard '*' examples of failed attempts include: (I can see why the first two shouldn't work)

grep "$Var1"*"$Var2" file.txt     
grep "$Var1*$Var2" file.txt
echo "$Var1*$Var2" | grep file.txt
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Giles
  • 897

1 Answers1

5

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.

Lesmana
  • 27,439