How to you combine all lines that end with a backslash character

awkperlsedtext processing

Using a common command line tool like sed or awk, is it possible to join all lines that end with a given character, like a backslash?

For example, given the file:

foo bar \
bash \
baz
dude \
happy

I would like to get this output:

foo bar bash baz
dude happy

Best Answer

a shorter and simpler sed solution:

sed  '
: again
/\\$/ {
    N
    s/\\\n//
    t again
}
' textfile

or one-liner if using GNU sed:

sed ':x; /\\$/ { N; s/\\\n//; tx }' textfile
Related Question