Linux 2个变量的乘法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9017478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiplication of 2 variables
提问by Andres
Supposingly I am working on one of my options in my program. I have a text file which has the below content.
假设我正在研究我的程序中的一个选项。我有一个包含以下内容的文本文件。
The format is Title:Author:Price:QtyAvailable:QtySold
, e.g.:
格式是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
Below is my function:
下面是我的功能:
printf "%-22s %-16s %-14s %-15s %-13s %s\n", "Title", "Author", "Price","Qty Avail.", "Qty Sold", "Total Sales"
grep "" 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
The problem is I need another column which is called Total Sales, computed by multiplying Price
and QtySold
. However I have tried different ways such as $Price * $QtySold
or $3 * $5
but still the program does not compute it out for me. Which should be the correct method or way to solve this?
问题是我需要另一列名为 Total Sales 的列,通过乘以Price
和来计算QtySold
。但是,我尝试了不同的方法,例如$Price * $QtySold
或$3 * $5
但该程序仍然没有为我计算出来。哪个应该是解决这个问题的正确方法或方法?
采纳答案by jham
You could use bc like this:
你可以像这样使用 bc:
printf "%-22s %-16s %-14.2f %-15d %-13d %0.2f %0.2f\n", "$Title" "$Author" "$Price" "$QtyAvailable" "$QtySold" "$(echo $QtySold*$Price | bc)"
回答by Sorin
use (())
使用(())
Example:
例子:
A=5 B=6 echo $(($A*$B))
30
For floating point numbers you should use awk or bc:
对于浮点数,您应该使用 awk 或 bc:
A=5.5 B=6; echo $A \* $B | bc
A=5.5 B=6; echo -e "$A\t$B" | awk '{print * }'
However, using awk for the entire script is better for your needs:
但是,对整个脚本使用 awk 更适合您的需求:
awk -F: 'BEGIN{ printf "%-50s %-16s %-14s %-15s %-13s %s\n",
"Title", "Author", "Price", "Qty Avail.", "Qty Sold", "Total Sales"}
~ search {printf "%-50s %-16s %12.2f %13d %10d %10.2f\n",
, , , , , * }' BookDB.txt search=Harry
Or if you wish perl, which is a bit shorter:
或者,如果你希望 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
回答by viggy
line=Lord of The Ring:Johnny Dept:56.80:100:38
线=指环王:约翰尼部门:56.80:100:38
echo $line | awk -F":" '{=*; print "*="}'
output: $3*$5=2158.4
输出:$3*$5=2158.4