3

If I have a file:

aaa / new replacement line
AAA / old target line
random line
random line 
BBB / old target line
CCC / old target line

In this example there are 4 replacements, so the final file should end up like:

aaa / new replacement line
aaa / new replacement line
random line
random line 
aaa / new replacement line
aaa / new replacement line

I have an attempt at an answer below but would like to see your input on this also. Maybe there is a more successful 'vim golf' approach I am unaware of. Maybe I'm just being really dumb and there is a simple command for this.

Basically, the question is this: if I have a line yanked into a register, how do I completely replace searched lines matching 'old target line'?

pb2q
  • 54,061
  • 17
  • 135
  • 139
Kevin Lee
  • 718
  • 6
  • 18

2 Answers2

6

Use 0y$ to yank your replacement line - this won't include the newline.

Then use:

%s/.*old target line.*/\=@"

To replace the target lines with the contents of the unnamed register, which will contain the last yank.

pb2q
  • 54,061
  • 17
  • 135
  • 139
0

I first grab the 'aaa / new replacement line' by using "aY, save into register a

Then I remove the carriage return using the following, from remove newlines from a register in vim?:

:let @a=substitute(strtrans(@a),'\^@',' ','g')

Or, I can simply use visual selection with v and grab the line without the return (this is much easier).

I can then use the global command to perform the replacement:

:g/old target line/s/.*/\=@a
Community
  • 1
  • 1
Kevin Lee
  • 718
  • 6
  • 18
  • One improvement is that I should use visual selection mode `v` and yank the line, hence removing the remove newlines from a register step. – Kevin Lee Jul 09 '12 at 22:12