A simple solution I could apply to join/concatenate 3 lines of text together using Vim

Viewed 82

I was looking for a simple solution I could apply to join/concatenate 3 lines of text together using Vim. I wanted to take a file containing 36 short strings and join every 3 lines, in effect producing just 12 longer lines. (For anyone reading this and wondering why - I was producing a markdown table around some shortcut commands). So the example is, I had wanted to take:

1 short-line one  
2 short-line two  
3 short-line three  

and have:

1 short-line one 2 short-line two 3 short-line three

across the file.

2 Answers

A simple solution I discovered was:

:%norm 3gJ

% is execute the following command from line 1 to the end. The norm command runs the normal mode commands equivalent to the letters that follow it. g and capital J is the shortcut for join and finally, the 3 is for three 3 lines.

I hope that this might be useful to someone else searching for a simple solution in the future.

You can do it manually by putting the cursor on the first line of the three to be joined.

Then type : followed by .,+2j!

. - Current line

+2 - To 3rd line from current

j! - Join the lines with adding spaces

j - joins adding spaces in between.

Transforms

1 short-line one  
2 short-line two  
3 short-line three  

to

1 short-line one  2 short-line two  3 short-line three

Or record a macro qq - Start recording (replace second q with any alphabetic character

Poistion cursor on first line to join and Type

`:.,+2j!`

Type q to stop recording

Then move to first lline of next block say on 4 short-line-one of the below

4 short-line one
5 short-line two
6 short-line three

Type @q to repeat macro.

You can make it repeatable but that's more than I have time for today

Related