Domanda

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.:

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 "$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

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?

È stato utile?

Soluzione

You could use bc like this:

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

Altri suggerimenti

use (())

Example:

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

For floating point numbers you should use awk or bc:

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

However, using awk for the entire script is better for your needs:

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

Or if you wish perl, which is a bit shorter:

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

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

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

output: $3*$5=2158.4

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top