Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

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

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.