Kevin Lee
Kevin Lee

Reputation: 718

How to replace searched lines with yanked line in vim?

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'?

Upvotes: 3

Views: 190

Answers (2)

Kevin Lee
Kevin Lee

Reputation: 718

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

Upvotes: 0

pb2q
pb2q

Reputation: 59607

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.

Upvotes: 6

Related Questions