I have a text file like this:

Line text,line text
 next line
 3rd line
Line x

where 2nd and 3rd, etc lines begin with a single space. I need to concatenate all lines prefixed with a space to the previous one without a space, so that the result looks like this:

Line text,line text next line 3rd line
Line x

The lengths of the lines can vary, and there can be many blocks like this. Can I re-format the entire file with a single command?

3 Answers 3


You can replace the new lines plus space by a space:

:%s/\n\s/ /

This is an ex command i.e. a command used in the command line mode. To enter the command line mode, press :. Then insert the command which does the following:

%        Apply the command on all the lines of the buffer
s/       The command to apply. 's' is for substitute
\n\s     The pattern to substitute here it is a new line \n followed by a space \s
/<space> The expression used to replace the pattern (here it is a simple space
/        The command must end with a / because you could add some flags

Please see :h :s


For every line beginning with a space, join it with the previous one:

:g/^ /-j


:help :global
:help pattern
:help [range]
:help :join

  • I like the global command, your solution is nice!
    – statox
    Jun 30, 2016 at 11:43

You can join lines with J. In your case:


Will join your 3 lines.

In the case you want more than 3 lines, you can do as follow:

  • enter visual mode
  • /^[^ ]/-1
  • J

This will select the desired lines and join them.

The search will look to the next line starting with a non-space character, and move up one line.

If you want to do this without entering visual mode, you can use the join command preceded by the desired range:

:,/^[^ ]/-1 j

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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