84

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', ]
Steven Lu
  • 41,389
  • 58
  • 210
  • 364
northtree
  • 8,569
  • 11
  • 61
  • 80

6 Answers6

124

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TWK
  • 1,264
  • 1
  • 8
  • 2
  • 5
    vipJ would be more efficient here. Or, if on the first line before the "[", v%J would work as well. Or, anywhere in the text block, va]J – Drasill Jul 06 '11 at 21:40
  • 2
    This should be upper case `J` and not lower case `j`. – d0m1n0 Sep 19 '19 at 13:02
56

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aaron Oommen
  • 770
  • 6
  • 9
17

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

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

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
jglouie
  • 12,523
  • 6
  • 48
  • 65
7

For that particular example, the following commands will work:

:1, 21 j

or

:%s/\n/ /g
James Nine
  • 2,548
  • 10
  • 36
  • 53
3
:g/\[/,/\]/j

Or

/^CATEGORIES

:v//-1j

And if you have:

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

:g/edit/,/next/j
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pooroldpedro
  • 181
  • 1
  • 4