为什么在grepping ps时,在正则表达式中用括号括起来的单个字符会排除grep本身? [英] Why does enclosing a single char in brackets in a regex exclude the grep itself when grepping ps?
问题描述
$ ps -ef |如果我在Linux机器上执行以下grep: 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中。但是,如果我在[bash]的任何字母周围放置[],我会得到:
$ bcode> $ 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组成的[]中的任何字符。
因为表达式 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
但是
wmiller 16220 6436 0 06:55 pts / 0 00:00:00 grep --color = auto ba [s] h
不匹配,因为它不完全是 bash
。
If I perform the following grep on my Linux box:
$ 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
Note the last line is reporting the grep itself because the word "bash" is in the args to grep.
But, if instead I put [] around any letter in "bash" I get:
$ 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
No info on the grep this time!
So, why does enclosing a letter in the search term, i.e. the regex, in brackets keep grep from reporting itself here? I though [s] meant "any character from the [] enclosed set consisting of the character "s".
This is because the expression ba[s]h
(or [b]ash
, or...) just matches bash
, not ba[s]h
(or [b]ash
, or...).
So the grep
command is looking for all lines with 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
but
wmiller 16220 6436 0 06:55 pts/0 00:00:00 grep --color=auto ba[s]h
does not match because it is not exactly bash
.
这篇关于为什么在grepping ps时,在正则表达式中用括号括起来的单个字符会排除grep本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!