84

如何在 中的选择范围内进行查找和替换vi

4

6 回答 6

99

在可视模式下选择文本(我假设这就是你正在做的事情),然后按下:开始输入命令,你会在命令行中看到类似这样的内容:

:'<,'>

这意味着该命令将应用于选择。然后输入s/search/replace/并回车。g(如果要替换所有匹配项,则在第三个斜线后添加 a ,c如果要对每个替换进行确认,请添加 a)

于 2009-04-21T15:25:50.123 回答
98

此处建议的大多数其他解决方案都适用于进行选择的整行,这可能不是您想要的。

要仅在选择中搜索和替换,首先直观地选择文本,然后使用如下命令:

:%s/\%VSEARCH/REPLACE/g

这将仅在视觉选择的部分中进行搜索和替换,将 SEARCH 替换为 REPLACE。如果您选择了多行,这也适用于多行。

于 2009-07-09T14:09:54.430 回答
23

如果您使用可视模式进行选择,则:

:'<,'>s/regex/replacement/options

如果您从可视模式'<,'>进入命令行模式(按), VIM 将自动放置范围 ( )。':'

于 2009-04-21T15:25:35.553 回答
8

此处提供更多帮助 在视觉选择中搜索和替换

于 2009-04-21T15:23:38.163 回答
2

The range of Ex commands are specified line-wise (see *cmdline-ranges*), and when : is pressed while there is a visual selection, the line range is automatically specified on the command line as '<,'> (see *v_:*), which makes the :s[ubstitute] command operate on the whole lines unless the visual selection boundaries are specified in the search pattern with \%V (see */\%V*), e.g. /\%Vvi\%Vm matches "vim" only within the visual selection, where the end of the selection is specified right before the end of the search pattern since each \%V specifies the next character as the start or end of the visual selection, and thus /\%Vvim\%V would require the visual selection to continue after 'm' to match "vim". Note that using the second \%V in a search pattern isn't necessary unless a match is required to be right at the border of or only partly in the visual selection.

于 2020-11-26T07:53:45.140 回答
-3

如果您想对文件中的所有实例进行全局搜索和替换(使用可选的正则表达式),我会执行以下操作:

:%s/foo/bar/g

省略 g 进行本地替换。

于 2009-04-21T15:28:20.087 回答