Friday, July 06, 2012

Use awk To grep "this but not that"

I've run into this situation several times over the decades, bit for some reason I never researched an elegant solution. Consider the case of grep'ing to see if a process is running. The simple solution is:
ps -ef | grep "ntpd" 
The problem is that if there is one process matching the regex, this will report two processes, because it will also report the grep process that is grep'ing the process stack. Its kind of like taking a picture of yourself in the mirror. The generic solution to this is:
ps -ef | grep "ntpd" | grep -v "grep" 
In other words, lets launch another grep to grep out the grep. This is only slightly less efficient than taking a picture of yourself in the mirror, then Photoshopping the camera out of the picture.

Today, I found the elegant solution, and its... awk to the resuce!
ps -ef | awk '/ntpd/ && !/awk/' 
Here, awk is taking the stream and searching for a line that has ntp and (&&) does not (!) have awk.


  1. give this a try
    ps -FC ntpd

    or replace the ntpd with apache or httpd

    not sure if this fits the bill

    1. Good one! The 'awk' example supports regex,
      but your suggestion looks like a solution for
      90% of the times I used 'ps' and 'grep'.