本文介绍了为什么在对 ps 进行 grepping 时,将单个字符括在正则表达式中的括号中会排除 grep 本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

请注意,最后一行是报告 grep 本身,因为bash"一词在 grep 的参数中.

Note the last line is reporting the grep itself because the word "bash" is in the args to grep.

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

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

这次没有关于 grep 的信息!

No info on the grep this time!

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

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".

推荐答案

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

This is because the expression ba[s]h (or [b]ash, or...) just matches bash, not ba[s]h (or [b]ash, or...).

所以 grep 命令正在寻找所有带有 bash 的行:

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

但是

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

不匹配,因为它不完全是 bash.

does not match because it is not exactly bash.

这篇关于为什么在对 ps 进行 grepping 时,将单个字符括在正则表达式中的括号中会排除 grep 本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:38