Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does enclosing a single char in brackets in a regex exclude the grep itself when grepping ps?

Tags:

regex

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

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

like image 316
Wes Miller Avatar asked Mar 23 '23 13:03

Wes Miller


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

like image 54
fedorqui 'SO stop harming' Avatar answered Apr 26 '23 08:04

fedorqui 'SO stop harming'


Fedorqui nails it with the explanation of the character class trick. I just wanted to point out the other method I used quite often albeit a bit longer than what you already know was to use -v option of grep command.

ps -ef | grep bash | grep -v grep
like image 33
2 revs Avatar answered Apr 26 '23 08:04

2 revs