1

I have a large list of scores that looks likes this:

Michelle
,46419
,32413
Frank
,46412
,33810
Steve
,28333
,17830
,37
Joe
,136
,93
Alicia
,121300
,84146

How can I move my list in Vim so it is re-arranged like this:

Michelle,46419,32413
Frank,46412,33810
Steve,28333,17830,37
Joe,136,93
Alicia,121300,84146

I've tried altering the list with this formula

:g/^,/s/$\n//g

But this doesn't get the lines with commas to fall in line behind the one ones without.

1
  • Not after the words, that was offered by Stackoverflow as a way to show a carriage return. Oct 13 '16 at 4:14
6

You can do this with a simple substitute command. Try this:

:%s/\n,/,

This removes a newline from every line containing a newline followed by a comma. You could also do it like this:

:%s/\n\ze,

The way this works is by marking the end of the selection to be removed, and the only text that will be removed is what matches before \ze. From :h /\ze

                                                        */\ze*
\ze Matches at any position, and sets the end of the match there: The
        previous char is the last char of the whole match. |/zero-width|
        Can be used multiple times, the last one encountered in a matching
        branch is used.
        Example: "end\ze\(if\|for\)" matches the "end" in "endif" and
        "endfor".
        This cannot be followed by a multi. |E888|
        {not in Vi} {not available when compiled without the |+syntax| feature}
0
4

@DJMcMayhem's solution is pretty good but Vim is pretty powerful so here is an alternative with the global command:

:g/^,/normal! kJ

That you can translate as "For every line which begins by a comma use the normal mode keys kJ i.e. to go the upper line and join it with the next one".

Edit As @Christian Brabandt said in the comments you can also use gJ which doesn't insert or remove any spaces, while J will remove indent and insert up to two spaces:

:g/^,/normal! kgJ

Finally to avoid using normal mode and shorten the command you could use the :join command (shortened to :j) with the range -1:

:g/^,/-1j

See :h J, :h gJ and :h :j

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.