linux script to update price

2019-06-10 21:23发布

i would like to do a code that prompts user to input the title and author of a book and i want to use grep to get the data based on just the title and author and echo it back for the user to see and edit the price without having the user to enter the old price

I need help in trying to get the $price Variable just by entering the title and author

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!"
}

标签: shell sed grep
2条回答
ら.Afraid
2楼-- · 2019-06-10 21:45

awk is better suited to extracting a field from the file and assigning it to a variable.

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!"
}
查看更多
女痞
3楼-- · 2019-06-10 21:51

In regards to the question above i came up with an answer for that. Hope it Helps

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

I manage to get the 3rd field of what the user input by matching it with the result line followed by using the sed line i edited the third field.

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!"   

}
查看更多
登录 后发表回答