4

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?

Sato Katsura
  • 4,009
  • 17
  • 24

3 Answers3

13

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

:g/^ /-j

References

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

Antony
  • 2,570
  • 11
  • 19
9

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

statox
  • 49,782
  • 19
  • 148
  • 225
5

You can join lines with J. In your case:

3J

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
nobe4
  • 16,033
  • 4
  • 48
  • 81