仅在找到匹配项的行中替换

pfn*_*sel 6 regex vim

,如何仅在匹配字符串的特定行上替换单词?例如,我有

replace here: foo
but not here: foo
replace again here: foo
Run Code Online (Sandbox Code Playgroud)

我想,以取代foobar在那里的字符串的所有行replace被发现,即输出应该是

replace here: bar
but not here: foo
replace again here: bar
Run Code Online (Sandbox Code Playgroud)

受到搜索和替换的类似启发,我曾期待

:/replace/s/foo/bar/
Run Code Online (Sandbox Code Playgroud)

工作,但它只在匹配的第一行进行替换replace.如何将其扩展到整个文档?

anu*_*ava 6

您可以使用g命令(全局)在多行中更改它:

:g/replace/s/foo/bar/
Run Code Online (Sandbox Code Playgroud)

  • 在`:s/foo/bar/g`中,`g`是一个标志.在`:g/replace/...`中,`g`是一个命令.从长远来看,如果你了解差异,你将更有效地使用vim. (2认同)