我在centos机器上有以下sh脚本:
echo "PID,CPU,MEM,PROC"
while [ 1 ]
do
ps aux | grep mysql | awk '{print $2",", $3",", $4",", $11}'
sleep 1
done
每个周期的输出都有这个输出:
1163, 0.0, 0.0, /bin/sh
1265, 0.0, 1.5, /usr/libexec/mysqld
11807, 0.0, 0.3, grep
我想知道如何循环输出并使用变量合并值并返回一行:我在合并结果中不需要PID和PROC
mysql, 0.0, 1.8
其中0.0是CPU(所有进程cpu使用总和)和1.8 RAM(所有进程ram使用总和)。
答案 0 :(得分:4)
ps -eo "comm %cpu %mem" --no-headers | awk '{a[$1] = $1; b[$1] += $2; c[$1] += $3}END{for (i in a)printf "%s, %0.1f, %0.1f\n", a[i], b[i], c[i]}' | sort
示例输出:
awk, 0.0, 0.0
bash, 0.0, 1.5
ps, 0.0, 0.0
sort, 0.0, 0.0
具体过程:
ps -C bash -o "comm %cpu %mem" --no-headers | awk '{a[$1] = $1; b[$1] += $2; c[$1] += $3}END{for (i in a)printf "%s, %0.1f, %0.1f\n", a[i], b[i], c[i]}'
输出:
bash, 0.0, 1.5