按命令组合Bash“ps”行

时间:2017-06-11 12:29:00

标签: linux bash

使用pstophtop时,如何在Linux Bash中合并相同程序的流程?

例如,当调用ps -eo pmem,pcpu,args代替此时:

...
2.0  1.0  /usr/sbin/apache2 -k start
3.0  2.0  /usr/sbin/apache2 -k start
5.0  1.0  /usr/sbin/apache2 -k start
2.5  1.0  /usr/sbin/mysqld
...

它会显示

...
10.0  4.0  /usr/sbin/apache2 -k start
 2.5  1.0  /usr/sbin/mysqld
...

将内存和CPU值相加。

也许有另一个命令来实现这个目标?

1 个答案:

答案 0 :(得分:1)

awk '{m=$1; c=$2; $1=$2=""; pmem[$0]+=m; pcpu[$0]+=c} END{for(i in pmem) {printf("%5.1f %5.1f %s\n",pmem[i], pcpu[i], substr(i,3))}}' file

输出:

 10.0   4.0 /usr/sbin/apache2 -k start
  2.5   1.0 /usr/sbin/mysqld

有一些评论:

awk '{m=$1; c=$2                # save column 1 and 2
     $1=$2=""                   # remove content of columns 1 and 2
     pmem[$0]+=m; pcpu[$0]+=c}  # save memory and cpu to hashes and
                                # add to its value, use rest of
                                # row as key

     # print content of both hashes and key in a loop
     END{for(i in pmem) {printf("%5.1f %5.1f %s\n",pmem[i], pcpu[i], substr(i,3))}}' file