Friday, November 11, 2011

Quick Tips - grep ps output

I use regular expressions in plenty of programs and scripts, but even more than that I use them on the command line. Here's a quick tip on grep'ing the output of ps.

Instead of this tired old command line trope:
ps -ef | grep foo | grep -v grep
try this:
ps -ef | grep '[f]oo'

$ ps -ef | grep vim
dg 14823 14739 0 15:12 pts/0 00:00:00 grep vim
dg 21295 13905 0 Nov09 pts/0 00:00:01 vim -R main.c
$ ps -ef | grep vim | grep -v grep
dg 21295 13905 0 Nov09 pts/0 00:00:01 vim -R main.c
$ ps -ef | grep '[v]im'
dg 21295 13905 0 Nov09 pts/0 00:00:01 vim -R main.c
This works because the regex [v]im contains a character class matching the single letter v. This will match the string vim in the ps output, but will not match the grep, i.e. the character class [v] does not match the string [v].

No comments:

Post a Comment