How do I join the next line when a line matches a regex for whole document in VI?
In normal mode, J
(as distinct from j
, which moves the cursor down one line) is used to join a line with the one directly beneath it. However, by default it adds a space to the end of the first line; to get the result you want (joining the lines without inserting an additional space), one would have to use gJ
.
In order to use normal-mode commands in ex-mode (which you enter by pressing :
while in normal mode), one must use the normal
command. See :h normal
within vim. So, to work with the next line that matches the pattern, one would use (note that by default, you have to escape the +
to get it to work with vim's regex, a consequence of maintaining compatibility with the original vi's ancient regex engine):
:/^a.\+g$/normal gJ
To work on every line that matches the pattern, one would use the :global
command (see :h :g
within vim) like so:
:global/^a.\+g$/normal gJ
Or, more concisely:
:g/^a.\+g$/norm gJ
It's also possible to use the ex command join
(see :h :join
) to achieve the same thing with very slightly less typing (the !
at the end, in this case, tells join
not to insert a space at the end of the first line).
:g/^a.\+g$/join!