1

如何计算以下数据?

Input:

2 Printers
2 x 2 Cartridges
2 Router
1 Cartridge

输出:

Total Number of Printers: 2
Total Number of Cartridges: 5 
Total Number of Router: 2

请注意,墨盒已成倍增加(2 x 2) + 1 = 5。我尝试了以下操作,但不确定当我有(2 x 2)场景类型时如何获取号码:

awk -F " " '{print $1}' Cartridges.txt >> Cartridges_count.txt
CartridgesCount=`( echo 0 ; sed 's/$/ +/' Cartridges_count.txt; echo p ) | dc`

echo "Total Number of Cartridges: $CartridgesCount"

请指教。

4

2 回答 2

1

这假设数据中只有乘法运算符。

awk '{$NF = $NF "s"; sub("ss$", "s", $NF); qty = $1; for (i = 2; i < NF; i++) {if ($i ~ /^[[:digit:]]+$/) {qty *= $i}}; items[$NF] += qty} END {for (item in items) {print "Total number of", item ":", items[item]}}'

分成多行:

awk '{
        $NF = $NF "s"; 
        sub("ss$", "s", $NF); 
        qty = $1; 
        for (i = 2; i < NF; i++) {
            if ($i ~ /^[[:digit:]]+$/) {
                qty *= $i
            }
        }; 
        items[$NF] += qty
     } 
     END {
         for (item in items) {
             print "Total number of", item ":", items[item]
         }
     }'
于 2012-05-15T21:24:32.140 回答
0

尝试这样的事情(假设输入格式良好)......

sed -e 's| x | * |' -e 's|^\([ 0-9+*/-]*\)|echo $((\1)) |' YourFileName | sh | awk '{a[$2]+=$1;} END {for (var in a) print a[var] " "var;}'

PS墨盒和墨盒是不同的。如果您也想处理它,那将更加困难,但您可以修改管道中的最后一个 awk。

于 2012-05-15T20:05:20.417 回答