2个变量的乘法

时间:2012-01-26 11:27:45

标签: linux shell unix command-line multiplying

假设我正在制定我的计划中的一个选项。 我有一个文本文件,其中包含以下内容。

格式为Title:Author:Price:QtyAvailable:QtySold,例如:

Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38

以下是我的功能:

printf "%-22s %-16s %-14s %-15s %-13s %s\n", "Title", "Author", "Price","Qty Avail.", "Qty Sold", "Total Sales"
grep "$1" BookDB.txt | while IFS=: read Title Author Price QtyAvailable QtySold; do
  printf "%-22s %-16s %-14.2f %-15d %-13d %0.2f\n", "$Title" "$Author" "$Price" "$QtyAvailable" "$QtySold"
done

问题是我需要另一个名为Total Sales的列,通过乘以PriceQtySold来计算。不过我尝试了$Price * $QtySold$3 * $5等不同的方法,但程序仍然没有为我计算出来。哪个应该是解决这个问题的正确方法或方法?

3 个答案:

答案 0 :(得分:6)

使用(())

示例:

A=5 B=6 echo  $(($A*$B))
30

对于浮点数,您应该使用awk或bc:

A=5.5 B=6; echo $A \* $B | bc
A=5.5 B=6;  echo -e "$A\t$B" |  awk '{print $1 * $2}'

但是,对整个脚本使用awk可以更好地满足您的需求:

awk -F: 'BEGIN{ printf "%-50s %-16s %-14s %-15s %-13s %s\n",
           "Title", "Author", "Price", "Qty Avail.", "Qty Sold", "Total Sales"}
         $1 ~ search  {printf "%-50s %-16s %12.2f   %13d   %10d  %10.2f\n",
            $1, $2, $3, $4, $5, $3 * $5}' BookDB.txt search=Harry

或者如果你想要perl,它有点短:

perl -an -F: -s -e 'BEGIN{ printf "%-50s %-16s %-14s %-15s %-13s %s\n", "Title", "Author", "Price", "Qty Avail.", "Qty Sold", "Total Sales"}' \ 
 -e 'printf "%-50s %-16s %12.2f   %13d   %10d  %10.2f\n",@F,$F[2]*$F[4] if /$search/' -- -search=Harry BookDB.txt

答案 1 :(得分:0)

line = The Ring of the Ring:Johnny Dept:56.80:100:38

echo $line | awk -F":" '{$6=$3*$5; print "$3*$5="$6}'

输出: $ 3 * $ 5 = 2158.4

答案 2 :(得分:-1)

你可以像这样使用bc:

printf "%-22s %-16s %-14.2f %-15d %-13d %0.2f %0.2f\n", "$Title" "$Author" "$Price" "$QtyAvailable" "$QtySold" "$(echo $QtySold*$Price | bc)"