2

enter image description hereproblem below:

Script: I execute ps command with pid,user... and I am trying to use awk to sum overall cpu utilization of different processes.

Command:

> $ps -eo pid,user,state,comm,%cpu,command --sort=-%cpu | egrep -v '(0.0)|(%CPU)' | head -n10 | awk '
> { process[$4]+=$5; }
> END{
>   for (i in process)
>   {
>     printf($1" "$2" "$3" ""%-20s %s\n",i, process[i]"   "$6) ;
>   }
> 
>    }' | sort -nrk 5 | head

Awk: Sum 5th column according to the process name (4th column)

Output:

 1. 10935 zbynda S dd              93.3   /usr/libexec/gnome-terminal-server
 2. 10935 zbynda S gnome-shell     1.9    /usr/libexec/gnome-terminal-server
 3. 10935 zbynda S sublime_text    0.6    /usr/libexec/gnome-terminal-server
 4. 10935 zbynda S sssd_kcm        0.2    /usr/libexec/gnome-terminal-server

As you can see, the fourth and the fifth columns are all good, but the other ones (rows/columns) are just the first entry from ps command. I should have 4 different processes as in the fourth column, but for example, the last column shows only one same process.

How to get other entries from ps command? (not only the first entry)

  • Please add output of `ps -eo pid,user,state,comm,%cpu,command --sort=-%cpu | egrep -v '(0.0)|(%CPU)' | head -n10` (no descriptions, no images, no links) and your desired output for that sample input to your question (no comment). – Cyrus Jun 06 '20 at 15:11
  • when you put `END` in awk it reads all records and then executes the next block. In your case value of `$1 ,2,3,6` are coming from the last record. – Digvijay S Jun 06 '20 at 15:16

2 Answers2

1

Try this

ps -eo pid,user,state,comm,%cpu,command --sort=-%cpu | egrep -v '(0.0)|(%CPU)' | head -n10 | awk '
 { process[$4]+=$5; a1[$4]=$1;a2[$4]=$2;a3[$4]=$3;a6[$4]=$6}
 END{
   for (i in process)
   {
     printf(a1[i]" "a2[i]" "a3[i]" ""%-20s %s\n",i, process[i]"   "a6[i]) ;
   }

    }' | sort -nrk 5 | head

an END rule is executed once only, after all the input is read.

Digvijay S
  • 2,665
  • 1
  • 9
  • 21
0

Your printf uses $6, which retains the value from the last line. Think you want to use "i" instead.

Of course $1, $2, and $3 have the same problem so you will need to preserve incoming values as well. An exercise to the student is to fix this.

Gilbert
  • 3,740
  • 17
  • 19