This question already has an answer here:

For the following example, where we have "\" at the end, the \ and EOL character should be removed.

line 1\
line 2
line 3
line 4\
line 5

Output should be

line 1 line 2
line 3
line 4 line 5

Using vi, I can get above stuff as under: :%s/\//n//g

But when I do it on the terminal is not working. Any suggestions?

marked as duplicate by don_crissti, Stéphane Chazelas sed Aug 2 '18 at 10:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Hmm... that Vi substitution does not work in any Vi editor I tried it in. You probably meant :%s/\\\n/ /g which would work in Vim but not in Vi.

$ sed '/\\$/{N;s/\\\n/ /;}' file
line 1 line 2
line 3
line 4 line 5

This detects whether the current line ends with a backslash, and if it does, it appends the next line (sed will add a newline character between them), replaces the backslash and newline with a space character.

This will fail if two consecutive lines have backslashes at the end. For that, use something like

sed ':top;/\\$/{N;s/\\\n/ /;btop;}' file

Here, if a line with backslash has been processed, the code jumps back to the start.

Annotated version af that last sed script:

:top;             # define label "top"
/\\$/{            # the line ends with backslash
    N;            # append next line to pattern space with embedded newline
    s/\\\n/ /;    # substitute backslash and newline with space
    btop;         # branch to "top"
                  # (implicit print)

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