How can I print all the lines between two lines starting with one pattern for the first line and ending with another pattern for the last line?
Update
I guess it was a mistake to mention that this document is HTML. I seem to have touched a nerve, so forget that. I'm not trying to parse HTML or do anything with it other than print a section of a text document.
Consider this example:
aaa
bbb
pattern1
aaa pattern2
bbb
ccc
pattern2
ddd
eee
pattern1
fff
ggg
Now, I want to print everything between the first instance of pattern1
starting at the beginning of a line and pattern2
starting at the beginning of another line. I want to include the pattern1
and pattern2
lines in my output, but I don't want anything after the pattern2
line.
pattern2
is found in one of the lines of the section. I don't want to stop there, but that's easily remedied by indicating the start of the line with ^
.
pattern1
appears on another line after pattern2
, but I don't want to look at that at all. I'm just looking for everything between the first instance of pattern1
and the first instance of pattern2
, inclusive.
I found something that almost gets me there using sed
:
sed -n '/^pattern1/,/^pattern2/p' inputfile.txt
... but that starts printing again at the next instance of pattern1
I can think of a method using grep -n ... | cut -f1 -d:
twice to get the two line numbers then tail
and head
to get the section I want, but I'm hoping for a cleaner way. Maybe awk
is a better tool for this task?
When I get this working, I hope to tie this into a git
hook. I don't know how to do that yet, either, but I'm still reading and searching :)
Thank you.