我有一个格式的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)才能更快地完成这一任务吗?谢谢
发布于 2014-04-14 13:57:34
您可以使用以下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发布于 2014-04-14 14:00:38
#!/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发布于 2014-04-14 14:26:01
纯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 KBhttps://stackoverflow.com/questions/23061865
复制相似问题