I have a file like the following and I would like to print the lines between two given patterns PAT1
and PAT2
.
You can do what you want with sed
by suppressing the normal printing of pattern space with -n
. For instance to include the patterns in the result you can do:
$ sed -n '/PAT1/,/PAT2/p' filename
PAT1
3 - first block
4
PAT2
PAT1
7 - second block
PAT2
PAT1
10 - third block
To exclude the patterns and just print what is between them:
$ sed -n '/PAT1/,/PAT2/{/PAT1/{n};/PAT2/{d};p}' filename
3 - first block
4
7 - second block
10 - third block
Which breaks down as
sed -n '/PAT1/,/PAT2/
- locate the range between PAT1
and PAT2
and suppress printing;
/PAT1/{n};
- if it matches PAT1
move to n
(next) line;
/PAT2/{d};
- if it matches PAT2
delete line;
p
- print all lines that fell within /PAT1/,/PAT2/
and were not skipped or deleted.