linux 更新价格的脚本

linux script to update price

我想编写一个代码,提示用户输入一本书的标题和作者,我想使用 grep 仅根据标题和作者获取数据,并将其回显给用户查看并在无需用户输入旧价格的情况下编辑价格

我需要帮助来尝试通过输入标题和作者来获取 $price 变量

function update_cost
{
   echo "Title: "
   read title
   echo "Author: "
   read author
   grep -iqs "$title:$author:$price:" BookDB.txt && echo "$title:$author:$price:"
   echo "New Price: "
   read price_r
   sed  -i "/^$title:$author:/ s/$price/$price_r"  BookDB.txt || tee BookDB.txt && echo "Book Price has been    updated sucessfully!"
}

awk 更适合从文件中提取字段并将其分配给变量。

function update_cost
{
   echo "Title: "
   read title
   echo "Author: "
   read author
   price=$(awk -F: -v title="$title" -v author="$author" ' == title &&  == author { print  }' BookDB.txt)
   echo "Old price is $price"
   echo "New Price: "
   read price_r
   sed  -i "/^$title:$author:/ s/:$price:/:$price_r:/"  BookDB.txt || tee BookDB.txt && echo "Book Price has been updated sucessfully!"
}

关于上面的问题,我想出了一个答案。希望对你有帮助

 price=$(echo "$result" | cut -f 3 -d ":")

我设法通过将用户输入的第三个字段与结果行匹配,然后使用我编辑了第三个字段的 sed 行来获取用户输入的第三个字段。

function update_cost
{
   echo "Enter Title: "
   read title
   echo "Enter Author: "
   read author
   result=$(grep -ise "$title\:$author" BookDB.txt)
   price=$(echo "$result" | cut -f 3 -d ":")
   grep -iqs "$title:$author:$price:" BookDB.txt && echo "Book Found!"      
   echo "New Price: "
   read new_price
   sed -i "/^$title:$author:$price:/ s/$price/$new_price/" BookDB.txt || tee BookDB.txt && echo "Price has been updated sucessfully!"   

}