1

I'm trying without success to copy & paste pattern in all lines using a vim let say I've a text file which looks like this:

Hello name is Mishal
Hello name is jon
Hello name is dod
Hello name is joli
Hello name is sara 

I want to copy last pattern or any other pattern in each line and put it back in middle in the same line. so that it looks like:

Hello Mishal name is Mishal
Hello jon name is jon
Hello dod name is dod
Hello joli name is joli
Hello sara name is sara

I know it can do it with other tools such as awk,sed,cut,paste and more but i need to do it with vim

  • You can use substitute: :%s/Hello name is \(.*\)/Hello \1 name is \1/ – pbogut May 3 '17 at 14:08
5

You can do it with macro. In normal mode type q plus any letter to start macro recording in register a.

Then move your cursor at the beginning of the line and do the following command :

3wyw^wPa

Explanation

  • So 3w move cursor to 3 word
  • yw copy word in registry
  • ^w go to the first non-blank character then move one word forward (you need to type ^ twice in order to make it works.
  • P paste word in current register before the cursor
  • a space add a space after last word

Then type q to stop recording macro. Get to beginning of the line then execute macro in register "a" @a and/or @@ to execute last macro.

I'm sure there is more elegant way to do this, but this one work pretty well.

  • This is very useful, but doesn't work, the words I need to copy/paste contain charters like - , # and some read it as word number 33 and other read it as 30 like that, cannot done will all lines – user3716621 Apr 21 '17 at 15:07
  • Still pretty clever. Upvote. – SDsolar Apr 21 '17 at 18:00
  • Go beyond simple word commands @user3716621. Use $ to get to the end of a line. Then 'vT y' as in 'visual To (space) yank-selection' (uppercase is reverse search) to highlight the final word back to the preceding space and yank it. Then navigate to where you want it and paste it in. – Shadoath Apr 21 '17 at 22:57
0

Try awk "as an external command" like this:

:%!awk '{print $1,$NF,$2,$3,$NF}'

 % ................... current file
 ! ................... filter
 $NF ................. last field on awk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.