Get lines between two patterns

You would use sed for a task like that. It supports a syntax like from lines matching AAA print everything up to and including a line matching XXX.

Alas your input is a bit ill-formed because the starting pattern AAA occurs twice without a matching XXX for the second AAA. sed default behavior is to match from the second AAA until the last line in the input when the XXX is not found after the second AAA. The details are explained in the last section of the sed faq.

But there is also a solution how to match only the first block: this code is directly taken from the FAQ and adopted to your question:

sed -n '/AAA/{:a; N;/XXX/! b a; p;} yourfile.txt'
  • /AAA/ and /XXX/ are sed expression to match your start and end line
  • /AAA/{:a;N;/XXX/! ba; ... } is a loop: from a line matching AAA it it
    • executes a N command reading the next line
    • if the line does not match /XXX/! (notice the ! which negates the match) it branches back (b) to label a reading the next line.
    • only when the line matches XXX we leave the branch loop and print p the lines

If your input has always a matching XXX for every AAA and those blocks are not nested, the command is much more intuitive:

sed -n '/AAA/,/XXX/ p' yourfile.txt

Leave a Comment