How do I join the next line when a line matches a regex for whole document in VI?

10,390

Solution 1

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!

Solution 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/
Share:
10,390

Related videos on Youtube

Xiaoge Su
Author by

Xiaoge Su

Updated on September 18, 2022

Comments

  • Xiaoge Su
    Xiaoge Su over 1 year

    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?

  • törzsmókus
    törzsmókus over 7 years
    thanks for the ex command. in wasavi, the normal command does not work, but join does.
  • Alex Leach
    Alex Leach over 6 years
    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...