Print all matching lines and the previous unindented line

awkgrepsedtext processing

For example, lets say I want to find all lines with 'matching' and the previous unindented lines in this text.

Container 1
   some text
   some text
   matching text
   some text
Container 2
   some text
   some text
Container 3
   some text
   matching text

The result I want would look like this

Container 1
   matching text
Container 3
   matching text

Is this possible?

Best Answer

awk '
    !/^[[:blank:]]/ {unindented = $0} 
    /matching/ && /^[[:blank:]]/ {print unindented; print}
' file

That remembers the last line that did not begin with whitespace. When you get to a matching line, use that value.

Related Question