Tigran
Tigran

Reputation: 3585

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?

Upvotes: 0

Views: 118

Answers (1)

Cyrus
Cyrus

Reputation: 88654

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

Upvotes: 1

Related Questions