Find and Replace in Vim / Vi

Find and Replace in Vim / Vi

命令格式

:[range]s/{pattern}/{string}/[flags] [count]

可以在normal 模式下输入 :help substitute 查看帮助文档

示例 释义
:s/Foo/bar/ 当前行的第一个 Foo 替换成 bar,默认大小写敏感(I)
:s/Fo/bar/i 当前行的第一个 Fo 或 fo 或 fO 或 FO 替换成 bar
:s/foo/bar/gic 当前行所有的 foo 替换成 bar, 忽略大小写,每次替换时需要手动确认(confirm)
:3,10s/foo/bar/g 3-10 行的所有 foo 替换成 bar
:.,+4s/foo/bar/g 当前行和接下来的 4 行,foo 替换成 bar
:.,$s/foo/bar/g 从当前行(.)到最后一行($),foo 替换成 bar
:%s/foo/bar/g 当前文件所有行(% 表示 1,$ 首行到末行)的 foo 都替换成 bar
:%s/^foo.*/Vim is the best/gc 正则匹配,文件中所有以 foo 开头的行替换成 "Vim is the best", 每次替换需要手动确认
:3s/foo/bar/ 2 3-4 行,每行的第一个 foo 替换成 bar,count 是 2
:5,20s/^/#/ 5-20 行,行首插入 #
:5,20s/^#// 5-20行,删掉行首的 #
:%s/apple|orange|mango/fruit/g 文件中的 apple 或 orange 或 mango 都换成 fruit
:%s/\s\+$//e 删掉每行结尾的空白字符, e 是让 vim 当找不到匹配时不要报错(When the search pattern fails, do not issue an error message and, in particular, continue in maps as if no error occurred. This is most useful to prevent the "No match" error from breaking a mapping.)

感觉 [count] 用处不大,它提供的功能已经被 range 给覆盖到了


posted on 2022-09-16 15:35  明天有风吹  阅读(36)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园