在 Vim 中替换字符或文本可以使用 替换命令(substitute),其基本语法为:
:[range]s/old/new/[flags]
1. 基本替换
命令 | 说明 |
---|---|
:s/foo/bar/ | 替换当前行的第一个 foo 为 bar |
:s/foo/bar/g | 替换当前行的 所有 foo 为 bar |
:%s/foo/bar/g | 替换 全文 的 foo 为 bar |
:5,10s/foo/bar/g | 替换第 5 行到第 10 行的 foo 为 bar |
2. 正则表达式替换
命令 | 说明 |
---|---|
:%s/^foo/bar/g | 替换所有 行首 的 foo 为 bar |
:%s/foo$/bar/g | 替换所有 行尾 的 foo 为 bar |
:%s/\<foo\>/bar/g | 替换 完整单词 foo 为 bar (不匹配 foobar ) |
:%s/foo/bar/gc | 替换时 逐个确认(y 替换,n 跳过) |
3. 特殊字符转义
如果替换内容包含 /
或特殊字符,可以用 \
转义,或换分隔符(如 #
):
:%s/http:\/\/example.com/https:\/\/new.site.com/g
:%s#http://example.com#https://new.site.com#g
4. 删除字符
命令 | 说明 |
---|---|
:s/foo//g | 删除当前行的所有 foo |
:%s/\s\+$//g | 删除全文行尾的 多余空格 |
5. 可视模式替换
- 按
Ctrl + V
进入块选择模式,选中多行。 - 输入
:s/foo/bar/g
,Vim 会自动填充为:'<,'>s/foo/bar/g
,仅替换选中部分。
示例
Hello world
world is great
world of vim
-
替换全文
world
为Earth
::%s/world/Earth/g
结果:
Hello Earth Earth is great Earth of vim
-
仅替换第 2 行的
world
::2s/world/Earth/
总结
场景 | 命令 |
---|---|
当前行替换 | :s/old/new/ |
全文替换 | :%s/old/new/g |
带确认替换 | :%s/old/new/gc |
删除文本 | :s/old//g |
正则替换 | :%s/\<word\>/new/g |
Vim 的替换功能非常强大,结合正则表达式可以高效处理复杂文本!