My program should be able to work this way.
Below is the content of the text file named BookDB.txt
The individual are separated by colons(:) and every line in the text file should serve as a set of information and are in the order as stated below.
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
I actually intend to
1) Read the file line by line and store it in an array
2) Display it
However I have no idea on how to even start the first one.
From doing research online, below are the codes which I have written up till now.
#!/bin/bash
function fnReadFile()
{
while read inputline
do
bTitle="$(echo $inputline | cut -d: -f1)"
bAuthor="$(echo $inputline | cut -d: -f2)"
bPrice="$(echo $inputline | cut -d: -f3)"
bQtyAvail="$(echo $inputline | cut -d: -f4)"
bQtySold="$(echo $inputline | cut -d: -f5)"
bookArray[Count]=('$bTitle', '$bAuthor', '$bPrice', '$bQtyAvail', '$bQtySold')
Count = Count + 1
done
}
function fnInventorySummaryReport()
{
fnReadFile
echo "Title Author Price Qty Avail. Qty Sold Total Sales"
for t in "${bookArray[@]}"
do
echo $t
done
echo "Done!"
}
if ! [ -f BookDB.txt ] ; then #check existance of bookdb file, create the file if not exist else continue
touch BookDB.txt
fi
"HERE IT WILL THEN BE THE MENU AND CALLING OF THE FUNCTION"
Thanks to those in advance who helped!
Since your goal here seems to be clear, how about using
awkas an alternative to usingbasharrays? Often using the right tool for the job makes things a lot easier!The following
awkscript should get you something like what you want:The second section of code (between curly braces) runs for every line of input.
printfis for formatted output, and uses the given format string to print out each field, denoted by$1,$2, etc. Inawk, these variables are used to access the fields of your record (line, in this case).substr()is used to truncate the output, as shown below, but can easily be removed if you don’t mind the fields not lining up. I assumed “Total Sales” was supposed to be Price multiplied by Qty Sold, but you can update that easily as well.Then, you save this file in
books.awkinvoke this script like so:The
-F:tellsawkthat the fields are separated by colon (:), and-f books.awktellsawkwhat script to run. Your data is held inbooks.Not exactly what you were asking for, but just pointing you toward a (IMO) better tool for this kind of job!
awkcan be intimidating at first, but it’s amazing for jobs that work on records like this!