我有一个格式为的helpfile1:
client1 bla blahblah 2542 KB
client1 bla blahblah 4342 MB
client1 bla blahblah 7 GB
client2 bla blahblah 455 MB
client2 bla blahblah 455 MB
...
我需要获得每周大小
client1 SUM xy KB
client2 SUM yx KB
目前正在使用:
sumfunction ()
{
inputfile=helpfile1
for i in `awk -F":" '{print $1}' $inputfile| sort -u | xargs`
do
awk -v name=$i 'BEGIN {sum=0};
$0~name {
print $0;
if ($5 == "GB") sum = sum + $4*1024*1024;
if ($5 == "MB") sum = sum + $4*1024;
if ($5 == "KB") sum = sum + $4};
END {print name " SUM " sum " kB"}' $inputfile
done
}
sumfunction | grep SUM | sort -g -r -k 3 > weeklysize
我需要在相当长的文件上使用它,这个awk花费了太多时间。是否有其他代码(仅限bash),以更快地完成此操作?谢谢
答案 0 :(得分:5)
您可以使用以下awk脚本:
awk '/MB$/{$4*=1024};/GB$/{$4*=1024*1024};{a[$1]+=$4}END{for(i in a){printf "%s %s KB\n",i, a[i]}}' a.txt
以这种格式看起来更好:
/MB$/ {$4*=1024}; # handle MB
/GB$/ {$4*=1024*1024}; # handle GB
# count KB amount for the client
{a[$1]+=$4}
END{
for(i in a){
printf "%s %s KB\n",i, a[i]
}
}
输出
client1 11788782 KB
client2 931840 KB
答案 1 :(得分:4)
#!/usr/bin/awk -f
BEGIN {
output_unit = "KB"
modifier["KB"] = 1
modifier["MB"] = 1024
modifier["GB"] = 1024**2
}
NF { sums[$1] += modifier[$5] * $4 }
END {
for (client in sums) {
printf "%s SUM %d %s\n", client, sums[client]/modifier[output_unit], output_unit
}
}
注意:
NR { [...] }
)output_unit
(KB
,MB
,GB
)来配置输出单元$ ./t.awk t.txt
client1 SUM 11788782 KB
client2 SUM 931840 KB
答案 2 :(得分:3)
Pure Bash(4.0 +):
declare -Ai client # associative array
while read c1 c2 c3 c4 c5 ; do
if [ -n "$c5" ] ; then
if [ $c5 = 'KB' ] ; then
client[$c1]+=$c4
elif [ $c5 = 'MB' ] ; then
client[$c1]+=$c4*1024
elif [ $c5 = 'GB' ] ; then
client[$c1]+=$c4*1024*1024
fi
fi
done < "$infile"
for c in ${!client[@]}; do # print sorted results
printf "%s %20d KB\n" $c ${client[$c]}
done | sort -k1
输出
client1 11788782 KB
client2 931840 KB