1
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================

我想更新 QTY,在这种情况下是 197 的值,但我似乎无法用我的程序更新值,请帮助我,因为我刚刚开始学习 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
4

3 回答 3

1

您在第一个字符类之后缺少一个星号。并且不要忘记扩大小组。

于 2013-07-25T05:06:12.283 回答
0

重构使用grep -q;修正if成语;将搜索锚定到行首;使用read -p而不是单独的echo;捕获括号内的价格,以免丢失;在正则表达式中添加缺少的重复;并在新的数量值后添加分隔冒号;另外,添加一个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
}
于 2013-07-25T05:15:44.297 回答
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
===============================
于 2013-07-25T05:30:19.510 回答