3

How can I make tools like grep treat multilines escaped with a backslash as a long single line?

Let's say I have some files that looks like this:

testvar=test1 \
        test2 \
        test3

othervar=oth1 \
         oth2

If I now grep for testvar it will return testvar=test1 \, but is there any way I can have it return testvar=test1 test2 test3?

More or less how to treat those multiple escaped lines as a single line?

Note: If this can't be done with grep, hints about how to do this with other tools like sed or awk to get the same result are also welcome.

2 Answers 2

3

With awk setting the field separator and record separators to your use case:

awk 'BEGIN { FS="\n"; RS ="" } /testvar/' yourfile
testvar=test1 \
        test2 \
        test3

See the manual entry for multiple line records.

2

You can preprocess it with something that joins those lines, like:

awk 'match($0,/\\+$/) && RLENGTH % 2 {
       sub(/\\$/,""); printf "%s", $0; next
     }
     {print}' | grep ...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .