简体   繁体   中英

Combine rows of Bash “ps” by command

How to combine processes of the same program in Linux Bash when using ps , top or htop ?

For example, when called ps -eo pmem,pcpu,args instead of this:

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

it would show

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

with memory and CPU values summed.

Maybe there is another command to achieve this?

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

Output:

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

With some comments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM