简体   繁体   English

Shell脚本中的输出过滤

[英]Output filtering in shell scripting

in my script file 在我的脚本文件中

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

i am running this command less XYZ.TXT | 我少运行此命令XYZ.TXT | grep BPR | grep BPR | awk -F'CACH' {'print $1'}, and i get out put like this. awk -F'CACH'{'print $ 1'},我就这样输出了。

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

From these out put i need to calculate amount from each line and total amount as out put. 从这些输出中,我需要从每一行计算出的金额以及输出的总金额。

for example 例如

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

and final out put should be the total amount. 最后输出应该是总数。 How can i do this. 我怎样才能做到这一点。 please help me. 请帮我。

Try with two sub() functions. 尝试使用两个sub()函数。 The first one to remove all characters until a non-zero number. 第一个删除所有字符直到一个非零数字的字符。 And the second one to add the decimal point: 第二个添加小数点:

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

It yields: 它产生:

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

Try following: 请尝试以下操作:

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

Input data: 输入数据:

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

Output: 输出:

2781.99

If you want output at every step: 如果要在每个步骤输出:

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

Output: 输出:

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

Instead of 代替

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

say

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

EDIT: In order to get the total, say 编辑:为了得到总数,说

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM