VKA
VKA

Reputation: 319

Calculation with in Bash Shell

How can I calculate following data?

Input:

2 Printers
2 x 2 Cartridges
2 Router
1 Cartridge

Output:

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

Please note that Cartridges have been multiplied (2 x 2) + 1 = 5. I tried following but not sure how to get the number when I have (2 x 2) type of scenario:

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"

Please advise.

Upvotes: 1

Views: 242

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360055

This assumes that there are only multiplication operators in the data.

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]}}'

Broken out on multiple lines:

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]
         }
     }'

Upvotes: 1

amit_g
amit_g

Reputation: 31250

Try something like this (assuming a well formatted input) ...

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;}'

P.S. Cartridges and Cartridge are different. If you want to take care of that too, it would be even more difficult but you can modify the last awk in the pipeline.

Upvotes: 0

Related Questions