【问题标题】:How can I exclude results from a process count containing specific arguments?如何从包含特定参数的进程计数中排除结果?
【发布时间】:2014-11-26 21:11:33
【问题描述】:

我正在计算这样的过程:

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

但这包括my_script.php foo=1my_script.php foo=1&bar=2 的结果。

如何区分这些计数?我想分别计算有多少包含参数bar 与不包含bar 的参数。

假设上述ps aux... 返回 2(一个带有参数 bar,一个没有),我如何一次搜索每个?

期望的结果:(带有明显的假占位符用于说明)

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

更新

我可以像这样粗略地排除 bar 结果:

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

显然,当脚本名称或路径可能包含bar 字符串时,这将不起作用,但现在它对我有用。我所追求的主要是如何计算相反的值。也就是只包括bar的那些怎么算。

【问题讨论】:

  • grep [m]yscript.php 将避免使用grep -v grep。您可能还希望 [m]yscript\\.php 匹配文字 .
  • 向您的模式添加更多或使用多个 grep 通道来获得不同的计数。您的占位符基本上就是您所需要的(当重写为 grep 模式时)。
  • 对,我实际上可以得到包含bar 的那些就好了。我只包括grep -v bar。但是我怎样才能得到相反的结果呢?
  • grep -v bar排除其中包含 bar 字样的那些。 grep bar包含其中包含bar 的那些。
  • 你可能想看看pgrep

标签: regex grep ps wc


【解决方案1】:

这有帮助吗?

ps aux|grep -Pc 'my_script[.]ph[p].*[\s&]bar='
  • -P 使用 perl 正则表达式
  • [.] 使其匹配文字点,而不是任何单个字符
  • ph[p] 过滤掉 grep 进程本身
  • [\s&]bar= 这匹配一个空或 & + bar=
  • -c 只返回匹配的行数

一个例子,(模拟你的 ps 输出的文本文件):

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

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多