Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================
我想在这种情况下更新值为197的QTY,但我似乎无法用我的程序更新值,请帮助我,因为我刚开始学习shell编程。感谢
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
答案 0 :(得分:1)
在第一个字符类之后,你错过了一个星号。不要忘记扩大小组。
答案 1 :(得分:0)
重构使用grep -q
;修复if
成语;将搜索锚定到行首;使用read -p
代替单独的echo
;抓住parens里面的价格,这样它就不会丢失;在正则表达式中添加缺少的重复;并在新的qty值后添加分隔符冒号;另外,添加一个else
子句,以便该函数不会无声地失败。
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
}
答案 2 :(得分:0)
以下是您对awk
:
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
$ 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
===============================