Both Ex commands and command-line commands are the same. They are the commands that start with a colon (:).
:g/pattern/command
The global command works by executing command against each line that matches the pattern
:g/console/d
remove all lines containing "console"
在运行g命令时,Vim对文件进行两次扫描。在第一次运行时,它扫描每一行并标记与/console/模式匹配的行。一旦标记了所有匹配的行,它将第二次执行,并在标记的行上执行d命令。
run the global command on non-matching lines:
:g!/pattern/command
or
:v/pattern/command
:g/one|two/d
delete the lines containing either "one" or "two
:g/[0-9]/d
or
:g/\d/d
delete the lines containing any single digits
:g/0{3,6}/d
match the lines containing between three to six zeroes
.,3
between the current line and line 3
3,$
between line 3 and the last line
+n
n lines after the current line.
:g/./normal A;
add a ";" to the end of each line
/./ 是 “非空行”的模式。它匹配至少有一个字符的行,所以它匹配带有"const"和"console"的行,而不匹配空行。
宏
qa0A;<Esc>q
在寄存器a中创建一个宏,这些行末尾添加一个逗号
:g/const/normal @a
使用Recursive Global Command
:g/console/g/two/d
delete the second console.log
首先,g将查找包含模式“console”的行,并将找到3个匹配项。然后第二个g将从这三个匹配中寻找包含模式“2”的行。最后,它将删除该匹配。改变分隔符
:g@console@d
delete the lines containing "console"
g@one@s+const+let+g
using the substitute command with the global command, you can have two different delimiters
默认的命令
如果未指定命令,会执行输出命令
:g/console
print at the bottom of the screen all the lines containing "console".Reversing The Entire Buffer
:g/^/m 0
reverse the entire fileAggregating All TODOs
编写代码时,有时我会在正在编辑的文件中编写TODOs
const one = 1;
console.log("one: ", one);
// TODO: feed the puppy
const two = 2;
// TODO: feed the puppy automatically
console.log("two: ", two);
const three = 3;
console.log("three: ", three);
// TODO: create a startup selling an automatic puppy feeder
跟踪所有创建的todo可能很难。
要将所有TODOs复制到文件末尾,以便更容易地进行内省,运行:
:g/TODO/t $
结果:
const one = 1;
console.log("one: ", one);
const two = 2;
console.log("two: ", two);
const three = 3;
console.log("three: ", three);
// TODO: feed the puppy
// TODO: feed the puppy automatically
// TODO: create a startup selling an automatic puppy feeder
:g/console/d _
删除并不存储到寄存器中
减少多个空行为一个空行
:g/^$/,/./-1j
通常,全局命令接受以下格式::g / pattern / command。 但是,您也可以使用以下格式运行全局命令::g / pattern1 /,/ pattern2 / command。 这样,Vim将在pattern1和pattern2中应用命令:
/pattern1/是/^$/
它表示空行(带有零字符的行)。
/pattern2/ is /./ with -1 line modifier
表示非空行(至少有一个字符的行)。-1表示上面的一行。
command is j, the join command (:j).
在这个上下文中,这个全局命令连接所有给定的行。
:g/^$/,/./j
将多个空行减少为无行
- Advanced Sort
const arrayB = [
"i",
"g",
"h",
"b",
"f",
"d",
"e",
"c",
"a",
]
const arrayA = [
"h",
"b",
"f",
"d",
"e",
"a",
"c",
]
you need to sort the elements inside the arrays, but not the arrays themselves
:g/[/+1,/]/-1sort
结果:
const arrayB = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
]
const arrayA = [
"a"
"b",
"c",
"d",
"e",
"f",
"h",
]
- :g/[/
is the global command pattern. - /[/+1
第一个模式。它匹配左方括号“[”。+1指的是它下面的一行 。 - /]/-1
第二种模式。它匹配右方括号“]”。-1指的是它上面的一行。 - /[/+1,/]/-1
then refers to any lines between "[" and "]". - sort
is a command-line command to sort.