user3509528
user3509528

Reputation: 107

Find and replace a string when that line contains another string in VIM

I'm trying to figure out how to replace a word or string on each line in a file if it contains another string in vim. For example, given a file containing:

Hello World Test
This is a Hello Test
World This Test Hello a

I want to replace Test with Apple where that line contains the words Hello and World. I would use the search statement to find the lines that contain Hello and World (in no either order). But how would I go about coming up with a substitute for Test on those lines.

Example Find Statement:

/\(Hello.*World\)\|\(World.*Hello\)

Example Updated file

Hello World Apple
This is a Hello Test
World This Apple Hello a

Upvotes: 2

Views: 2460

Answers (1)

melpomene
melpomene

Reputation: 85757

You can use the :global command for that:

:g/Hello.*World\|World.*Hello/s/Test/Apple/g

Here we run the substitution command s/Test/Apple/g on all lines where Hello.*World\|World.*Hello matches.

Upvotes: 7

Related Questions