Mark Reed
Mark Reed

Reputation: 95242

Join groups of N lines

I have a text file generated from an old database that consists of one line per field, with no delimiter between records other than knowing how many fields there are. What I'd like to do is join the first N lines, and then the next N, and so on. Is there any way to do this within Vim? Is there were a way to select lines to apply a command to based on an arbitrary VimL expression (like line(".")%5==0) instead of just a regex?

Upvotes: 6

Views: 2366

Answers (2)

Alan Gómez
Alan Gómez

Reputation: 378

It can be done with two simple regex:

:%s/\(\(^.*\n\)\{5}\)/\1\r/g

This one just put a return every 5 line, followed by:

:%s/\(\n\{2}\)\|\n/\1/g

OR

:%s/\n\{2}\zs\|\n//g

This removes just 1 return character not 2 consecutive ones

Upvotes: 0

sidyll
sidyll

Reputation: 59277

There are multiple ways of solving this. First that comes to my mind is recording a macro, say in register w:

qw5Jjq

This essentially uses the J normal command to join 5 lines and moves one down. Then you can repeat the macro for 20 times with a simple 20@w or keep repeating afterwards with @@.

Another, maybe more "proper" way is using the :join ex command, which is the same as the J normal command, but can be abbreviated to :j and used in conjunction with the :g to operate in various lines. For example:

:g/./j5

This will match every line non-empty line and in each one of them, join the next 5 lines (inclusive). Then move to the next line and join more 5 and so on.

Upvotes: 13

Related Questions