gpt4 book ai didi

linux - 2个变量的乘法

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:07 26 4
gpt4 key购买 nike

假设我正在研究我的程序中的一个选项。我有一个包含以下内容的文本文件。

格式为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 但程序仍然没有为我计算出来。解决这个问题的正确方法或方法应该是什么?

最佳答案

使用(())

例子:

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

对于 float ,您应该使用 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

关于linux - 2个变量的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com