在 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 的替換功能非常強大,結合正則表達式可以高效處理復雜文本!