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]}'
source share