Say you have a long file and for some reason you want to get all the lines between two patterns.

Just to give you an example, consider the following text file: If you want to get all the lines, starting with the one containing the pattern “aa” (line 2) and ending with (and including) the one(s) containing the pattern “cc” (line 8), you might think of using the sed command: The main problem is that sed will stop when encountering the first line containing the “cc” pattern (line 6), and it will give you:
aa
aaaa
aaaaaaa
bbbb
cc
In order to make it go until the last line with the “cc” pattern, use the below hack:
  1. use grep to get all the lines with the “cc” pattern.
  2. Get the last line, using tail -1
  3. use the entire last line for sed
The end result should look something like this: And running the script should give you the desired result:
[labroot@centos-7 test1]$ ./test.sh
aa
aaaa
aaaaaaa
bbbb
cc
ccccc
cccccclast
Now, there may be a better way to do it, but honestly, this works for me so it’s good enough for now.