Why does including a single char in parentheses in a regular expression exclude grep itself when grepping ps?

If I use the following grep in 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 that the last line tells grep itself, because the word "bash" is in args for 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 

This time there is no information about grep!

So why the inclusion of letters in a search expression, i.e. regular expression in brackets does not allow grep to report about itself here? However, I meant "any character from the [] nested set consisting of the character" s ".

+4
source share
2 answers

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

+6
source

Fedorqui pushes him to explain the character class trick. I just wanted to point to another method that I used quite often, although a little longer than what you already know, is to use the -v version of the grep .

 ps -ef | grep bash | grep -v grep 
+1
source

Source: https://habr.com/ru/post/1486248/


All Articles