How can I exclude results from a process count containing specific arguments?

600 views Asked by At

I'm counting processes like so:

ps aux | grep my_script.php | grep -v grep | wc -l

But this includes results for both my_script.php foo=1 as well as my_script.php foo=1&bar=2.

How can I separate these counts? I'd like to count how many include the argument bar separately from those who do not include bar.

Assuming the above ps aux... returns 2 (one with the argument bar and one without), how can I search for each one at a time?

Desired result: (with obvious fake placeholder for illustration)

// list all my_script.php processes
$ ps aux | grep my_script.php | grep -v grep
root  10 ... Ss  14:34 0:53 php /path/to/my_script.php foo=1&bar=2
root  12 ... Ss  14:35 0:46 php /path/to/my_script.php foo=1
// returns 2 lines (this works)

// Just count just those including the `bar` argument
$ ps aux | grep my_script.php _____+bar_____ | grep -v grep | wc -l
// return 1

// Just count only those NOT including the `bar` argument
$ ps aux | grep my_script.php _____-bar_____ | grep -v grep | grep -v bar | wc -l
// return 1

UPDATE

I can crudely exclude bar results like so:

$ ps aux | grep my_script.php | grep -v grep | grep -v bar | wc -l

Obviously that won't work for times when the script name or path may include bar string, but for now it works for me. The main thing I'm after is how to count the opposite. That is, how to count those only including the bar.

1

There are 1 answers

0
Kent On BEST ANSWER

does this help?

ps aux|grep -Pc 'my_script[.]ph[p].*[\s&]bar='
  • -P use perl regex
  • [.] make it match literal dot, not any single character
  • ph[p] filter the grep process itself out
  • [\s&]bar= this matches an empty or & + bar=
  • -c return you only the number of matched lines

an example, (text file to simulate your ps output):

kent$  cat f
root  10 ... Ss  14:34 0:53 php /path/to/my_script.php foo=1&bar=2
root  12 ... Ss  14:35 0:46 php /path/to/my_script.php foo=1
root  12 ... Ss  14:35 0:46 php /path/to/my_script.php foobar=1
root  12 ... Ss  14:35 0:46 php /path/to/my_script.php bar=1

kent$  grep -Pc 'my_script[.]ph[p].*[&\s]bar=' f
2