我想做一个代码,提示用户输入书籍的标题和作者,我想使用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!"
}
答案 0 :(得分:1)
关于上述问题,我想出了一个答案。希望它有助于
price=$(echo "$result" | cut -f 3 -d ":")
我设法通过将其与结果行匹配,然后使用我编辑第三个字段的sed行来获取用户输入的第3个字段。
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!"
}
答案 1 :(得分:0)
awk
更适合从文件中提取字段并将其分配给变量。
function update_cost
{
echo "Title: "
read title
echo "Author: "
read author
price=$(awk -F: -v title="$title" -v author="$author" '$1 == title && $2 == author { print $3 }' 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!"
}