Getting memory usage from "ps aux" output with awk

I need to solve an exercise using awk. Basically, I need to extract the total amount of memory usage for each user from the ps aux command and format it like this:

User Total%Mem user1 3.4% user2 1.5% 

etc.

The problem that I can't seem to solve is this: how do I know how many users are logged in? And how can I make a different amount for each of them?

Thanks:)

+4
source share
3 answers

You do not need to know anything. All you need to know is:

  • You have column output with the same number of columns in each row.
  • The first column is the username.
  • The fourth column is the% MEM column.
  • Awk automatically initializes the variable to 0.
  • Awk index keys are arbitrary values ​​:)

     ps aux | awk 'NR != 1 {x[$1] += $4} END{ for(z in x) {print z, x[z]"%"}}' 

I connect the input to awk and then tell it to skip line 1 (NR! = 1). Then, for each individual line, it is read in English as follows:

in the array 'x', increase the value in 'x [username]' by the value in the 4th column. If the array key does not exist but create it by initializing to 0, and then increase this value by the 4th column.

When Awk did this for every single line, it runs the code in the "END" block, which says to print each username (z to x) and the final aggregated value associated with that user (x [z]), and then " % ".

If you want it to be built line by line, you can use the same basic rules, but add print after processing each line, and not in "END":

 ps aux | awk 'NR != 1 {x[$1] += $4; print $1, x[$1]}' 
+9
source

You must use associative arrays to accumulate memory usage for each user. You do not need to know how many users exist, because you can iterate over the array. Why don't you show what you still have?

Here is the basic structure in pseudocode that such a program would have:

 BEGIN { print headers, do other setup if needed } { add the %mem field to the array element indexed by the user name } END { for each element in the array print the name and the total add the total to a grand total print the grand total } 
+1
source
 ps -eo user,pmem| awk 'NR>1{u[$1]+=$2}END{for(i in u)print "user: "i",mem: "u[i]}' 
+1
source

Source: https://habr.com/ru/post/1307195/


All Articles