简体   繁体   中英

Linux bash scripting: Sum one column using awk for overall cpu utilization and display all fields

在此处输入图像描述 problem 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)

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.

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.

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