Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only in lines where match is found

Tags:

regex

vim

In vim, how can I replace a word only on specific lines where a string is matched? For example, I have

replace here: foo
but not here: foo
replace again here: foo

and I want to replace foo with bar on all lines where the string replace is found, i.e. the output should be

replace here: bar
but not here: foo
replace again here: bar

Inspired by the sed like syntax of vim's search and replace, I'd expected

:/replace/s/foo/bar/

to work, but it does the replacement only on the first line where it matches replace. How can I extend this to the whole document?

like image 463
pfnuesel Avatar asked Mar 15 '14 12:03

pfnuesel


1 Answers

You can use g command (global) for changing it in multiple lines:

:g/replace/s/foo/bar/
like image 161
anubhava Avatar answered Oct 18 '22 22:10

anubhava