如果我在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
Run Code Online (Sandbox Code Playgroud)
注意最后一行是报告grep本身,因为单词"bash"在args中为grep.
但是,如果相反我把[]放在"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
Run Code Online (Sandbox Code Playgroud)
这次没有关于grep的信息!
那么,为什么在搜索词中附上一个字母,即正则表达式,在括号中让grep不在这里报告?我虽然[s]的意思是"包含字符"s"的封闭集中的任何字符.
这是因为表达式ba[s]h
(或[b]ash
,或......)只匹配bash
,而不是ba[s]h
(或[b]ash
,或......).
所以该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
Run Code Online (Sandbox Code Playgroud)
但
wmiller 16220 6436 0 06:55 pts/0 00:00:00 grep --color=auto ba[s]h
Run Code Online (Sandbox Code Playgroud)
不匹配,因为它不完全bash
.