如何找到&在 Vim 中用一个表达式替换多个表达式?
我正在将一个示例从 PDF 复制粘贴到 Vim,我必须将所有 “
和 ”
替换为 "
以及所有 '
和 '
与 '
以便代码正常工作。
嗯,这可能看起来更容易理解: 我想同时用 foobar
替换所有 foo
和 bar
。
I am copy-pasting an example from a PDF to Vim and I have to replace all “
and ”
with "
and all ‘
and ’
with '
so that the code works.
Well that will probably seem easier to understand:
I want to replace all foo
and bar
with foobar
simultaneously.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
vi
中尝试一下:然后
Try this in
vi
:then
使用 tr 作为过滤器:
Unix 方式:
Use tr as a filter:
Unix way:
如果您想用“foobar”替换所有“foo”和所有“bar”,您可以使用:
%s/\v<(foo|bar)>/foobar/g
这将替换“foo”和“bar”,但将保留任何“foobar”。
%s/
- 替换整个文件\v
- 使用非常神奇的正则表达式语法(请参阅:help magic
了解更多信息)<
- 匹配左侧单词边界(foo|bar)
- foo 或 bar>
- 匹配右侧单词边界/foobar/< /code> - 替换字符串
g
- 全局(将会发生对于每一次出现,而不仅仅是该行中的第一个)请注意,如果您只是处理标点符号,您可能需要删除此正则表达式的单词边界部分,否则它将不起作用。
If you want to replace all "foo"s and all "bar"s with "foobar" you can use this:
%s/\v<(foo|bar)>/foobar/g
This will replace the "foo"s and the "bar"s but will leave any "foobar"s alone.
%s/
- substitute across the whole file\v
- use very magic regex syntax (see:help magic
for more info)<
- match a left word boundary(foo|bar)
- foo or bar>
- match a right word boundary/foobar/
- replacement stringg
- globally (will happen for every occurrence, not just the first on the line)Note that if you are just dealing with punctuation you'll probably want to remove the word boundary parts of this regex or it won't work.