4

如果我在我的 Linux 机器上执行以下 grep:

$ ps -ef | grep bash
root      2286     1  0 Jun06 ?        00:03:15 /bin/bash /etc/init.d/zxy100wd
wmiller   6436  6429  0 Jun06 pts/0    00:00:01 bash
wmiller  10707  6429  0 Jun07 pts/1    00:00:00 bash
wmiller  10795  6429  0 Jun07 pts/2    00:00:00 bash
wmiller  16220  6436  0 06:55 pts/0    00:00:00 grep --color=auto bash

请注意,最后一行是报告 grep 本身,因为“bash”一词在 grep 的 args 中。

但是,如果我将 [] 放在“bash”中的任何字母周围,我会得到:

$ ps -ef | grep ba[s]h
root      2286     1  0 Jun06 ?        00:03:15 /bin/bash /etc/init.d/zxy100wd
wmiller   6436  6429  0 Jun06 pts/0    00:00:01 bash
wmiller  10707  6429  0 Jun07 pts/1    00:00:00 bash
wmiller  10795  6429  0 Jun07 pts/2    00:00:00 bash

这次没有关于 grep 的信息!

那么,为什么将搜索词中的字母(即正则表达式)括在括号中会阻止 grep 在这里报告自己?我虽然 [s] 的意思是“来自 [] 封闭集中的任何字符,由字符“s”组成。

4

2 回答 2

6

这是因为表达式ba[s]h(or [b]ash, or...) 只匹配bash, 而不是ba[s]h(or [b]ash, or...)。

因此,该grep命令正在查找所有带有以下内容的行bash

root      2286     1  0 Jun06 ?        00:03:15 /bin/bash /etc/init.d/zxy100wd
wmiller   6436  6429  0 Jun06 pts/0    00:00:01 bash
wmiller  10707  6429  0 Jun07 pts/1    00:00:00 bash
wmiller  10795  6429  0 Jun07 pts/2    00:00:00 bash

wmiller  16220  6436  0 06:55 pts/0    00:00:00 grep --color=auto ba[s]h

不匹配,因为它不完全一致bash

于 2013-06-14T13:09:06.270 回答
1

Fedorqui用对角色类技巧的解释来说明这一点。我只是想指出我经常使用的另一种方法,尽管比您已经知道的使用命令-v选项要长一些grep

ps -ef | grep bash | grep -v grep
于 2013-06-14T23:09:46.717 回答