Grep with continuation lines

awkgrepsedtext processing

How can I grep/awk/sed a file looking for some pattern, and print the entire line (including continuation lines if the matched line ends with \?

File foo.txt contains:

something
whatever
thisXXX line \
    has a continuation line
blahblah
a \
multipleXXX \
continuation \
line

What should I execute to get (not necessarily in one line, not necessarily removing multiple spaces):

thisXXX line has a continuation line
a multipleXXX continuation line

BTW I'm using bash and fedora21, so it does not need to be POSIX-compliant (but I'll appreciate a solution if it is POSIX)

Best Answer

Another approach using perl to remove newlines that are preceded by \ and whitespace:

$ perl -pe 's/\\\n/ /' file | grep XXX
thisXXX line      has a continuation line
a  multipleXXX  continuation  line

To remove extra spaces, pass it through sed:

$ perl -pe 's/\\\n/ /' file | grep XXX | sed 's/  */ /g'
thisXXX line has a continuation line
a multipleXXX continuation line
Related Question