Pages

17 January 2010

grep [s]tring anyone?

This is another grep's adventure. It started from a thought: "is there a simple way so that when I grep for something, let's say ps output, grep itself isn't shown there?"

My usual recipe is like below:

$ ps auxw | grep httpd | grep -v grep

But recently I found a neat trick:

$ ps auxw | grep [h]ttpd

Why is that working? Imagine that in the previous command , "ps auxw" would output these two lines among others:

mulyadi 30632 0.0 0.0 5852 1516 pts/8 Ss+ Jan09 0:00 httpd
mulyadi 30950 0.0 0.0 5852 1420 pts/9 Ss+ Jan07 0:00 grep httpd 

When you find for httpd, of course both of them will be caught because both of them has "httpd" string. The situation change for the 2nd command:

mulyadi 30632 0.0 0.0 5852 1516 pts/8 Ss+ Jan09 0:00 httpd
mulyadi 30950 0.0 0.0 5852 1420 pts/9 Ss+ Jan07 0:00 grep [h]ttpd

'What, how come?" you say? Recall you invoke "grep [h]ttpd", right? So, that's what displayed in ps. But grep interpret this regular expression differently. It means "I search for httpd", not "[h]ttpd". Everything enclosed in [] is something to search for, unless the "[" or "]" is escaped.

Clever trick I would say.... took me a while to understand it.

8 comments:

D P said...

hi,
I often do grep for text.
One particular feature i look for is numbering the results.

Eg.
# grep title /boot/grub/menu.lst
title RHEL 4
title RHEL 5
..

I would prefer the result to be something like:

# grep title /boot/grub/menu.lst
1 title RHEL 4
2 title RHEL 5
..

Do you know the magic option?

Thanks
Durga Prasad

Mulyadi Santosa said...

Hi Durga...

I think you can simply pipe the grep results to "cat -n".

regards,

Mulyadi.

Lane said...

By complete randomness (clicking next blog because I was bored) I came across this. And I do it all the time! I'm always trying to do that in scripts. Thanks!

Mulyadi Santosa said...

Hi Lane...

Thanks for visiting and leaving comment on my blog. Please don't hesitate if you have further comments in the future. Always glad to receive constructive feedback.

regards,

Mulyadi.

wsxwhx701 said...

IS VERY GOOD..............................

joven said...

hi, you have nice blog.. u can view also mine..http://akoniwares.blogspot.com

Anonymous said...

Hi,

You can try also:

ps aux | awk '/nfsd/ && !/awk/'

Have fun,
Stephan.

Mulyadi Santosa said...

Hi Stephan

Nice tips too! :) Thanks a lot