2

How to copy the current line content to the end of each line for the whole file ? For example:

From

hello 
world 
!

To

hello     hello 
world     world 
!         !

2 Answers2

3

Handling text in columns is what Visual-Block mode is made for!

You can create a blockwise Visual selection for all your text with:

  • gg to go to the Top; then
  • Ctrl+V to start Visual Block mode. (You might see -- VISUAL BLOCK -- at the last line of the screen.)
  • G to go to the last line of the buffer.
  • $ to select until the end of each line. This is pretty important! Since lines might have different number of characters, the $ behaves in a special way, in that instead of forcing a rectangle format to the selection, it extends it to the longest line, whatever number of columns it has.

Once you got everything selected in a Visual Block, you can use y to yank it into the unnamed register.

At that point, when you put it, it will come back as a block, as a column.

Go back to the first line, using gg, then append a certain number of spaces to get you to the column where you want your second copy to appear. For example, for 20 spaces, you can use 20A then Space and Esc.

At that point, you can go to the end of that line with $ and simply put with p. Sine the register was yanked in Visual Block mode, Vim will remember that and put the contents as a column. Lines that need to be extended with spaces to make it to allow for the pasted text to start in the later column will get extended automatically.

Also useful (with the Visual Block mode) is the 'virtualedit' option, which lets you navigate the cursor past the end of lines. If you enable it with :set virtualedit=all, then you can skip the part about adding enough spaces to the first line, since you can simply navigate to the appropriate column and the act of pasting the Visual Block contents with p will extend the first line with spaces as well.

filbranden
  • 8,522
  • 2
  • 16
  • 32
0

:%s/^\(.*\)$/\1 \1

  • % - whole file
  • s/^\(.*\)$ - match line from the beginning to end
  • /\1 \1 - replace it with matched text two times.

There may be a problem with formatting those lines in columns. Here is an example:

hello           hello
hello           hello
world           world
!           !

This can be solved with addition of trailing spaces, the the shorter lines, like this: (. - denotes trailing space)

hello           hello
hello           hello
world           world
!....           !....    

As mentioned by @mattb in the comment, column formatting issue can be fixed with column command (it has to be on your PATH though): :%s/^\(.*\)$/\1 \1/ | %!column -t

Monsieur Merso
  • 1,459
  • 1
  • 15
  • 18