我有一个由另一个人的脚本生成的文件,如下所示:(高度截断的示例)
Usage by user / host / workspace directory:
adallman:
sideshow:
bob 12065 MB
mel 488 MB
simpsons:
bart 32965 MB
afkham:
simpsons:
lisa 102466 MB
agnewjo:
flanders:
ned 70847 MB
rod 2657 MB
ahoang:
flanders:
rod 2896 MB
akrishna:
flanders:
ned 3310 MB
moes:
barney 1850 MB
carl 15674 MB
lenny 10723 MB
sideshow:
bob 0 MB
mel 101700 MB
simpsons:
bart 0 MB
lisa 0 MB
所以换句话说用户在上面的文件中我们可以解释我们所看到的,即..,
User:
Host:
Workspace: <size on that workspace MB>
我希望输出看起来像这样:(截断)
adallman: <total in GB>
afkham: <total in GB>
agnewjo: <total in GB>
ahoang: <total in GB>
我只想总结每个用户的总数。
请记住,我可以总结创建一个这样的用户列表:
ypcat passwd | cut -d: -f1 > valid_users
并得到这样的东西:(截断的)
zahrobsk
mylonopo
alindema
sutterk
sstslim
wleung
pazgil
答案 0 :(得分:2)
这可以是一种方式:
$ awk '!/^ / {name=$1; next} NF==3{a[name]+=$2} END {for (i in a) print i, a[i]/1024, "GB"}' file
adallman: 44.4512 GB
ahoang: 2.82812 GB
afkham: 100.064 GB
akrishna: 130.134 GB
agnewjo: 71.7812 GB
答案 1 :(得分:0)
Pure bash解决方案(从 stdin 读取文件):
#!/bin/bash
valid_users=$( ypcat passwd | cut -d: -f1 )
declare -A sizes
while read username size foo
do
if [ "$foo" = "MB" ]
then
let sizes[$username]=$(( sizes[$username] + $size ))
fi
done
for i in $valid_users
do
GB=$(( ${sizes[$i]:-0} / 1024 ))
echo "$i: $GB"
done