shell脚本中的输出过滤

时间:2013-10-08 11:08:13

标签: bash shell unix awk

在我的脚本文件中

for file in *.TXT
do
    echo "put $file"
    less $file | grep BPR | awk -F'CACH' {'print $1'}
done

我正在运行此命令减去XYZ.TXT | grep BPR | awk -F'CACH'{'print $ 1'},我就这样出来了。

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

从这些输出我需要计算每行的金额和总金额。

例如

BPRC000000000008801         88.01
BPRC000000000006671         66.71
BPRP000000000005088         50.88
BPRC000000000004542         45.42
BPRP000000000003805         38.05
BPRC000000000013624         136.24
BPRC000000000235668         2356.68

并且最终输出应该是总金额。我怎样才能做到这一点。请帮帮我。

3 个答案:

答案 0 :(得分:1)

尝试使用两个sub()函数。第一个删除所有字符直到非零数字。第二个添加小数点:

awk '
    BEGIN { OFS = "\t" } 
    { $2 = $1; 
      sub( /^[^0]*0*/, "", $2 ); 
      sub( /..$/, ".\&", $2 ); 
      print $0 
    }
' data

它产生:

BPRC000000000008801     88.01
BPRC000000000006671     66.71
BPRP000000000005088     50.88
BPRC000000000004542     45.42
BPRP000000000003805     38.05
BPRC000000000013624     136.24
BPRC000000000235668     2356.68

答案 1 :(得分:1)

请尝试以下操作:

awk -F'[A-Z]+' '{total += $2/100} END {printf "%.2f", total}' data

输入数据:

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

输出:

2781.99

如果你想在每一步都输出:

awk -F'[A-Z]+' '{printf "%s\t%.2f\n",$0, $2/100; total += $2/100} END {printf "Total = %.2f\n", total}' data

输出:

BPRC000000000008801     88.01
BPRC000000000006671     66.71
BPRP000000000005088     50.88
BPRC000000000004542     45.42
BPRP000000000003805     38.05
BPRC000000000013624     136.24
BPRC000000000235668     2356.68
Total = 2781.99

答案 2 :(得分:1)

而不是

awk -F'CACH' {'print $1'}

awk -F'CACH' '{c=$1;sub(/[^0-9]*/,"",c);}{print $1, c/100}'

编辑:为了获得总数,请说

awk -F'CACH' '{c=$1;sub(/[^0-9]*/,"",c);total+=c/100}{print $1, c/100}END{printf "%.2f", total}'