vim 中 :g 和 :%s 命令有什么区别 [英] What is the difference between :g and :%s commands in vim
问题描述
今天我开始使用vim.我对 :g
和 :%s
命令感到困惑.那么,:g
或 :%s
命令之间有什么区别?
today I started to use vim. I get confused at :g
and :%s
commands. So, what is the difference between :g
or :%s
commands?
推荐答案
:g
,global
的缩写,在所有匹配正则表达式的行上执行命令:
:g
, short for global
, executes a command on all lines that match a regex:
:g/LinesThatMatchThisRegex/ExecuteThisCommand
示例:
:g/hello/d
这将删除 (d
) 所有包含 hello 的行.
This will delete (d
) all lines that contain hello.
另一方面,:%s
只是执行搜索(在正则表达式上)并替换整个文件:
On the other hand, :%s
just performs a search (on a regex) and replace throughout the file:
:%s/hello/world/g
末尾的 g
表示 global
或 greedy
(这是有争议的),因此它将替换该行上出现的所有内容,而不仅仅是每行一个.如果您想手动确认每次替换,您也可以使用 c
标志 (:%s/hello/world/gc
).
The g
at the end means global
or greedy
(this is disputed) so it will replace all occurrences on the line, not just one per line. You can also use the c
flag (:%s/hello/world/gc
) if you want to confirm each replacement manually.
此命令将所有出现的 hello
替换为 world
.
This command replaces all occurrences of hello
with world
.
:g
和 :%s
命令都支持正则表达式.
Both the :g
and :%s
commands support regular expressions.
s
命令意味着 substitute
和 %
意味着整个缓冲区.所以 %s
意味着在整个缓冲区中替换.您还可以给出一个行范围:
The s
command means substitute
and the %
means throughout the buffer. So %s
means substitute throughout the entire buffer. You can also give a line range:
:10,15s/hello/world/g
这将仅在第 10 行到第 15 行(包括第 10 行到第 15 行)执行之前看到的搜索和替换.
This will execute the search and replace seen earlier on only lines 10 to 15 (inclusive).
这篇关于vim 中 :g 和 :%s 命令有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!