And*_*res 1 unix linux shell 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
Run Code Online (Sandbox Code Playgroud)
以下是我的功能:
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
Run Code Online (Sandbox Code Playgroud)
问题是我需要另一个名为Total Sales的列,通过乘以Price和计算得出QtySold.不过,我已经尝试了不同的方式,如$Price * $QtySold或$3 * $5但仍程序不计算出来我.哪个应该是解决这个问题的正确方法或方法?
使用(())
例:
A=5 B=6 echo $(($A*$B))
30
Run Code Online (Sandbox Code Playgroud)
对于浮点数,您应该使用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}'
Run Code Online (Sandbox Code Playgroud)
但是,对整个脚本使用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
Run Code Online (Sandbox Code Playgroud)
或者如果你想要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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13217 次 |
| 最近记录: |