How can I merge multiple lines into one line in Vim?

Vim

Vim Problem Overview


For example, I want to merge such text:

CATEGORIES = ['Books',
        'Business',
        'Education',
        'Entertainment',
        'Finance',
        'Games',
        'Healthcare & Fitness',
        'Lifestyle',
        'Medical',
        'Music',
        'Navigation',
        'News',
        'Photography',
        'Productivity',
        'Reference',
        'Social Networking',
        'Sports',
        'Travel',
        'Utilities',
        'Weather',
        'All',  ]

into

CATEGORIES = ['Books', 'Business', 'Education', 'Entertainment', 'Finance', 'Games', 'Healthcare & Fitness', 'Lifestyle', 'Medical', 'Music', 'Navigation', 'News', 'Photography', 'Productivity', 'Reference', 'Social Networking', 'Sports', 'Travel', 'Utilities', 'Weather', 'All', ]

Vim Solutions


Solution 1 - Vim

In command mode:

[range]j[lines]

For example: here you want to do the whole buffer:

%j

If you just wanted to do 10 lines from the current cursor position:

j10

If you don’t want to replace the new lines with spaces, use ! after j.

%j!
j!10

And for the uberfancy:

5j20

It would go to line 5, and join the next 20 lines.

Solution 2 - Vim

The most intuitive approach would be to use Vim visual line mode, Shift + v. All you have to do is select the content you want to merge to one line, and then press Shift + j.

Solution 3 - Vim

Use the J (uppercase) key. It will join the lines for you

Check this thread for more join options, and see the help page.

Solution 4 - Vim

For that particular example, the following commands will work:

:1, 21 j

or

:%s/\n/ /g

Solution 5 - Vim

:g/\[/,/\]/j

Or

/^CATEGORIES

:v//-1j

And if you have:

edit "Komputer" 
    ala 
    ala 
next 
edit "FortiGate" 
    ala 
    ala 
next

:g/edit/,/next/j

Solution 6 - Vim

Or to join everything from the opening square bracket to the closing square bracket (assuming you have lots of these in your file) and leaving other lines intact,

:g/\[/,/\]/j

is quick and simple.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnorthtreeView Question on Stackoverflow
Solution 1 - VimTWKView Answer on Stackoverflow
Solution 2 - VimAaron OommenView Answer on Stackoverflow
Solution 3 - VimjglouieView Answer on Stackoverflow
Solution 4 - VimJames NineView Answer on Stackoverflow
Solution 5 - VimMirosław LeszczyńskiView Answer on Stackoverflow
Solution 6 - VimpooroldpedroView Answer on Stackoverflow