I have lines like
abcdefg
join!
abcdef
no join
abcdefg
join!
If a line matches regex ^a.+g$
then I would like them to be joined, so it would be:
abcdefgjoin!
abcdef
no join
abcdefgjoin!
Is there a way of doing that in VIM
?
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!
normal
command does not work, but join
does.
Commented
Jan 11, 2017 at 19:44
A "pure" regex solution would be
:%s/^\(a.\+g\)\n/\1/
The advantage it has is that you can use it to extract a desirable string from the target line and combine it with the following line; for instance to trim off trailing whitespace
:%s/^(a.\+g\)[ \t]\+\n/\1/