7

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?

2 Answers 2

15

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!
2
  • thanks for the ex command. in wasavi, the normal command does not work, but join does. Jan 11, 2017 at 19:44
  • Neither of these seem to work for joining consecutive lines. If I have n lines in a row matching the pattern, I have to repeat the command roughly n/2 times...
    – Alex Leach
    Nov 28, 2017 at 14:45
2

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/

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.