Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================
I want to update the QTY which is the value of 197 in this case but i cant seems to be able to update the value with my program please help me as i have just started learning shell programming. Thanks
function update_qty_available
{
grep -c "$title:$author" BookDB.txt > /dev/null # Look for a line with matching values
if [ $? == 0 ];
then # If found then offer to change Qty
echo "Update Qty to what?"
read newQty
sed -i "s/\($title:$author\):[^:]:[^:]*:/\1:$newQty/" BookDB.txt
echo "Book's Qty has been updated successfully!"
fi
Refactored to use grep -q
; fix the if
idiom; anchor the search to start of line; use read -p
instead of a separate echo
; capture the price inside the parens so that it's not lost; add the missing repeat in the regex; and add back the separator colon after the new qty value; also, add an else
clause so that the function doesn't fail silently.
function update_qty_available
{
if grep -q "^$title:$author:" BookDB.txt
then
read -p "Update Qty to what?" newQty
sed -i "s/^\($title:$author:[^:]*\):[^:]*:/\1:$newQty:/" BookDB.txt
echo "Book's Qty has been updated successfully!"
else
echo "$0: BookDB.Txt: no '$title' by '$author'" >&2
fi
}
You're missing an asterisk after the first character class. And don't forget to expand the group.
Here is how you'd do with awk
:
Content of script.awk
:
BEGIN {
FS=OFS=":"
printf "Enter the book's name: "
getline name < "-"
printf "Enter author's name: "
getline author < "-"
printf "Enter new quantity: "
getline newQty < "-"
}
$1==name && $2==author { $4=newQty }1
Run:
$ cat BookDB.txt
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================
$ awk -f script.awk BookDB.txt
Enter the book's name: harry potter
Enter author's name: james
Enter new quantity: 5000
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:5000:101
===============================