Awk script always prints sum = 0
Sorry if the question might be silly, but I'm completely new to awk scripts. What I want to do is to calculate and print the CPU and memory usage of the "root" user. I wrote this bash script that executes an awk script:
#!/bin/bash
ps aux > processi.txt
echo Lancio script3.awk
awk -f script3.awk processi.txt
and the awk script:
#!/usr/bin/awk
BEGIN{
print "Inizio script\n"
cpu=0
mem=0
}
/root/{
printf("Cpu usata da root loop=%.1f, memoria=%.1f\n",$3,$4)
cpu=cpu+$3
mem=mem+$4
}
END{
printf("Cpu usata da root=%.1f, memoria=%.1f\n",$cpu,$mem)
print "\nFine script\n"
}
But the seal c END
is equal 0
, and b /root/
is correct. Any advice?
source to share
$
not used to expand variables in awk
, where it signals the expansion of a specific input field, the number of which is contained in the given variable. That is, if cpu=3
, then it is $cpu
equivalent $3
. Just use the variable name yourself.
END {
printf("Cpu usata da root=%.1f, memoria=%.1f\n", cpu, mem)
print "\nFine script\n"
}
source to share
The initial approach seems like overkill. Usage can extract required fields for username root
directly via parameters ps
:
All work:
ps U root -eo %cpu,%mem --no-header | awk 'BEGIN{ print "Inizio script\n" }
{ printf("Cpu usata da root loop=%.1f, memoria=%.1f\n",$1,$2); cpu+=$1; mem+=$2; }
END { printf("Cpu usata da root=%.1f, memoria=%.1f\n\nFine script\n", cpu, mem) }'
-
U root
- select data for username onlyroot
-
-eo %cpu,%mem
- display only field valuescpu
andmem
source to share
While this does not address your question as such, an additional suggestion that will not fit into the comment would be: formatting your code consistently will make your code easier to read and debug .
Same:
#!/usr/bin/awk
BEGIN {
print "Inizio script\n"
cpu = 0
mem = 0
}
/root/ {
printf("Cpu usata da root loop=%.1f, memoria=%.1f\n", $3, $4)
cpu = cpu + $3
mem = mem + $4
}
END {
printf("Cpu usata da root=%.1f, memoria=%.1f\n", cpu, mem)
print "\nFine script\n"
}
where I
- indented anything inside
{}
to level - put spaces around type operators
=
and+
- enter spaces between block labels and opening
{
- put spaces after
,
in argumentsprintf()
- also removed an outsider
$
mentioned in another answer.
source to share