In vim, I want to replace newlines with the literal string \n.

For example, if I open a file that contains this text:

This is line one
This is line two

I want to replace the newlines and have the following:

This is line one\nThis is line two

How can I achieve this?

  • Does it need to be done in vim? Can it just use sed on the file itself? Mar 11 '20 at 2:35

You have to escape the replace part of your substition with \



:            start an ex command
1,$-1        over a range from the first line till the last but one
s/           substitute
\n           all newlines
/            with
\\n          literal string \n
  • 1
    This will add an extra \n after the last line of the file. In the example given, it will end in two\n. (This might be fine, but it's slightly different from what was asked in the question.) Also, it would be good to start with a : to indicate this is an Ex command.
    – filbranden
    Mar 11 '20 at 3:33
  • 1
    @filbranden - You are right offcourse, the last line doesn't necessarely has a newline but in most cases it would. I have adjusted the answer to address the last newline. Mar 11 '20 at 5:23

Have a look at this:


This won't replace at the end of the file, so:

This is line one\nThis is line two\nThis is line three
  • You have a syntax error here, there's no / in between - and s, so that makes this command fail. Also, you don't need /g here since there's only one \n to match per line... Kudos on handling the last line correctly with $- though!!!
    – filbranden
    Mar 11 '20 at 3:35
  • 1
    @filbranden Thanks! I edited the answer. Mar 11 '20 at 11:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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