Join lines split with backslash at the end

sed -e '/\\$/{:0;N;s/\\\n//;t0}'
Joins each line that end with backslash (common way to mark line continuation in many languages) with the following one while removing the backslash.
Sample Output
$ sed -e '/\\$/{:0;N;s/\\\n//;t0}' <<END
> Hello \\
> world!
> END
Hello world!
$ echo 'scale=70; 127/131' | bc | sed -e '/\\$/{:0;N;s/\\\n//;t0}'
.9694656488549618320610687022900763358778625954198473282442748091603053

9
By: mwgamera
2011-10-09 14:35:23
sed

1 Alternatives + Submit Alt

What Others Think

Very nice. Could you now explain how it works :-)
flatcap · 345 weeks ago
PS, your first example is bogus (the second one's good). When you enter text as a 'here document' the shell interprets and leaves a string with an embedded newline (but no backslash). A simple proof is this: cat <<END > Hello \ > World > END Hello World
flatcap · 345 weeks ago
Thanks for pointing it out. I fixed the example. It works like this: When a line ending with backslash is read, it reads and appends the following line to the pattern space (the N command) and removes the backslash-newline sequence (s) from the resulting pattern. Finally, before continuing to the next input line, it repeats everything until substitution does not make any changes (t0 conditionally jumps to the :0) so lines spanning over more than two input lines are correctly joined into single output line.
mwgamera · 345 weeks ago
Ah, I understand. I bow to you sed mastery!
flatcap · 344 weeks and 6 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands



Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: