使用bash从文件中读取数据并使用awk获取某些列的总和

时间:2013-01-23 13:26:38

标签: bash unix awk

假设我想在.txt文件中收集一些统计信息,如下所示:

misses 15
hit 18
misses 20
hit 31

我写了一个只打印每一行的bash脚本:

#!/bin/bash 
while read line           
do           
    echo $line 
done <t.txt 

我现在想要的是:示例是伪代码:

read every line
   if first column is miss add the number to total misses
   if hits add the number to total hits

print total hits, and total misses in a file

我已经搜索过,这可以用awk完成。 你能帮助用awk做这件事吗?

4 个答案:

答案 0 :(得分:2)

只需将您的算法翻译为bash:

#!/bin/bash 
while read what count ; do           
    case $what in
        (hit)    let total_h+=count ;;
        (misses) let total_m+=count ;;
        (*)      echo Invalid input >&2; exit ;;
    esac
done < t.txt
echo Hits: $total_h, Misses: $total_m

答案 1 :(得分:2)

不需要任何bash gubbins,awk会做到这一切

awk 'BEGIN{ hits=0; misses=0; }/^hit/{ hits+=$NF}; /^misses/{misses=$NF}; END {print "Hits: " hits "\nMisses: " misses }' txtfile

这一个班轮的3个部分:

BEGIN{ hits=0; misses=0; }

在awk从txtfile读取任何行并初始化两个变量命中和未命中之前,只运行一次。

/^hits/{ hits+=$NF}; /^misses/{misses=$NF};

在每一行上运行,如果该行以命中开头,则最后一列被添加到hits变量,如果它以未命中开头,那么未命中变量将添加最后一列。

END {print "Hits: " hits "\nMisses: " misses' }

仅在处理完所有行后运行并打印出详细说明命中和未命中的消息。

答案 2 :(得分:2)

awk '/misses/||/hit/{a[$1]+=$2}END{print "total hits",a["hit"],",and total misses",a["misses"]}' your_file

测试:

> cat temp
misses 15
hit 18
misses 20
hit 31
hait 31
> awk '/misses/||/hit/{a[$1]+=$2}END{print "total hits",a["hit"],",and total misses",a["misses"]}' temp
total hits 49 ,and total misses 35

答案 3 :(得分:0)

declare misses=0 hit=0
while read var val; do
    let $var+=val
done < f.txt
echo "Misses: $misses"
echo "Hits: $hit"