2

I got the following data in a txt file,

Apple:Fruit:20:30
Leek:Vegetable:40:50

In a form where, (item description):(item category):(qty):(price). How to draw a table using shell script. Having an output

Item Description           Category          Qty       Price        Total Sales
--------------------------------------------------------------------------------
Apple                      Fruit             20         $30.00         $600.00
Leek                       Vegetable         40         $50.00         $2000.00

where Total sales is equal to qty x price. Please help. Thanks in advance!

3 Answers 3

3

This could get you started

awk '{printf "%-27s%-18s%-11s$%-14.2f$%.2f\n",$1,$2,$3,$4,$3*$4}' FS=: foo.txt

Result

Apple                      Fruit             20         $30.00         $600.00
Leek                       Vegetable         40         $50.00         $2000.00
Sign up to request clarification or add additional context in comments.

1 Comment

where to specify the file? Under FS?
2

I would perform the calculating and currency formatting in awk, use column for the table spacing and then sed to add the line:

awk -F: -v OFS=: '
    BEGIN {print "Item Description","Category","Qty","Price","Total Sales" }
    { $(NF+1) = $3*$4; $4 = sprintf("$%.2f", $4); $5 = sprintf("$%.2f", $5); print }
' file.txt |
column -s: -t | 
sed '1{p;s/./-/g}'
Item Description  Category   Qty  Price   Total Sales
-----------------------------------------------------
Apple             Fruit      20   $30.00  $600.00
Leek              Vegetable  40   $50.00  $2000.00

Comments

1

You can do it with awk, but it's much cleaner and simpler (and reliable) to use column to calculate the column sizes:

awk 'BEGIN { FS=":" ; print "Item description:Category:Qty:Price:Total sales"}
    {printf("%s:%s:%i:$%.2f:$%.2f\n",$1,$2,$3,$4,$3*$4)}' INPUTFILE | column -t -s:

I'm leaving the printing of the separator line to you (e.g. capture columns output with awk, after the first line calculate the length of $0, etc.)

1 Comment

How to print the seperator? Tried putting \n then followed by dashes but it did not get me far.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.