2012-01-26 65 views
1

假設我正在使用我的程序中的一個選項。 我有一個文本文件,其中包含以下內容。2個變量的乘法

格式爲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 

的問題是我需要另一列被稱爲總銷售額,乘以PriceQtySold計算。不過,我嘗試過不同的方式,例如$Price * $QtySold$3 * $5,但該程序仍然無法爲我計算出來。哪個應該是解決這個問題的正確方法或方法?

+0

這是你使用,bash shell的? – stdcall

+0

@Mellowcandle是的,我使用bash。 – Andres

+0

@andres請記住,儘管今天你使用的是bash,但確保你的代碼是可移植的sh是非常好的做法。 Bash提供了一些(次要的)方便,但它們只能用於命令行。 –

回答

-1

您可以使用BC這樣的:

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

它不工作,我試過。 它打印出來(40.30 * 50),而不是生成40.30 * 50的結果。:( – Andres

+0

對不起,我不應該混用zsh和bash。但是這也可以用bash。 '「$(echo $ QtySold * $ Price | bc)「' – jham

+0

它也起作用,謝謝!:) – Andres

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 
+0

試圖編譯,但顯示此錯誤。 line90L 40.30 * 50:語法錯誤:算術運算符無效(錯誤標記爲「.30 * 50」) 下面是導致錯誤的行。 – Andres

+0

printf「%-22s%-16s%-14.2f%-15d%-13d%0.2f \ n」, 「$ Title」「$ Author」「$ Price」「$ QtyAvailable」「$ QtySold」$( $ Price * $ QtySold)) – Andres

+2

@Andres:bash不支持浮點數。完全一樣。爲此,必須使用外部工具。 – Sorpigal

0

線=的指環王:約翰尼部門:56.80:100:38

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

輸出: $ 3 * 5 $ = 2158.4