通过bash脚本计算文件中的数字

时间:2018-01-14 20:13:17

标签: bash shell awk

我的文件包含以下内容。  例如2张图片尺寸为FRAGMENT。我想用bash脚本计算片段总大小。

ForEach ($emailAddress in $list) { 
    if (IsValidEmail($emailAddress)) { 
        "Valid: {0}" -f $emailAddress
        Out-File -Append C:\Emails\ValidEmails\ValidEmails.csv -Encoding UTF8
        $EmailAddressImp | Export-Csv "C:\Emails\ValidEmails\ValidEmails.csv" 
        -NoTypeInformation
    } 
    else { 
        "Invalid: {0}" -f $emailAddress 
        Out-File -Append C:\Emails\InValidEmails\InValidEmails.csv -
        Encoding UTF8
        $EmailAddressImp | Export-Csv 
        "C:\Emails\InValidEmails\InValidEmails.csv" -NoTypeInformation
    }     
}                                         

输出应该是这样的:

IMAGE admindb1 8 admindb1_1514997916 bus 4 Default-Application-Backup 2 3 1 1517676316 0 0
FRAG 1 1 10784 0 2 6 2 HSBRQ2 fuj 65536 329579 1514995208 60 0 *NULL* 1517676316 0 3 1 *NULL*

IMAGE admindb1 8 admindb1_1514995211 bus 4 Default-Application-Backup 2 3 1 1517673611 0 0
FRAG 1 1 13168256 0 2 6 12 HSBQ8I fuj 65536 173783 1514316708 52 0 *NULL* 1517673611 0 3 1 *NULL*
FRAG 1 2 24288384 0 2 6 1 HSBRJ7 fuj 65536 2 1514995211 65 0 *NULL* 0 0 3 1 *NULL*
FRAG 1 3 24288384 0 2 6 1 HSBRON fuj 65536 2 1514995211 71 0 *NULL* 0 0 3 1 *NULL*
FRAG 1 4 13806752 0 2 6 1 HSBRRK fuj 65536 2 1514995211 49 0 *NULL* 0 0 3 1 *NULL*

应该计算以FRAG开头的第4列。

我的脚本无效:

For Image admindb1_1514997916  total size is 10784
For Image  admindb1_1514995211  total size is 75551776

4 个答案:

答案 0 :(得分:2)

awk 'function summary() {print "For Image",image,"total size is",sum} 
     $1=="IMAGE" {image=$4}                         
     $1=="FRAG" {sum+=$4} 
     $1=="" {summary(); sum=0}
     END{summary()}' file

输出:

For Image admindb1_1514997916 total size is 10784
For Image admindb1_1514995211 total size is 75551776

我假设最后一行不是空的。

答案 1 :(得分:0)

cat -s file.txt | sed -n '/^IMAGE /{s:^[^ ]*  *[^ ]*  *[^ ]*  *\([^ ]*\).*$:echo -n "For image \1 total size is "; echo `echo ":;s:\*::g;p};/^$/{s:^:0"`|bc:;p};/^FRAG /{s:^[^ ]*  *[^ ]*  *[^ ]*  *\([^ ]*\).*$:\1\+:;s:\*::g;p};' | bash

输出:

For image admindb1_1514997916 total size is 10784
For image admindb1_1514995211 total size is 75551776

答案 2 :(得分:0)

Awk 解决方案:

awk '/^IMAGE/{ 
         if (t) { printf "For image %s total size is %d\n",img,t; t=0 } img=$4 
     }
     /^FRAG/{ t+=$4 }
     END{ if (t) printf "For image %s total size is %d\n",img,t }' file

输出:

For image admindb1_1514997916 total size is 10784
For image admindb1_1514995211 total size is 75551776

答案 3 :(得分:0)

cut GNU sed的粗略组合,(不小心使用e 评估)和{{ 3}}:

cut -d' ' -f4 file | datamash --no-strict transpose | 
sed 's#\tN/A\t#\n#g;y#\t# #' | 
sed 's/ \(.*\)/ $((\1))/;y/ /+/;s/+/ /;
     s/\(.*\) \(.*\)/echo For image \1  total size is \2/e'

输出:

For image admindb1_1514997916 total size is 10784
For image admindb1_1514995211 total size is 75551776

datamash更好。这个答案显示了sed的一些限制。此外,如果数据文件很大(比如数百万个数字总和),那么用于对shell添加的e 评估可能会超出其命令行长度限制。< / p>