Bash-使用sed替换确切的单词

时间:2015-07-27 09:56:44

标签: bash sed

我有一个格式为

的文本文件
Title : Author : Price : Quantity Avilable : Sold
Happy Day:Mary Ann:12.99:197:101
Happy Day:Mary Am:12.99:197:101

我有图书更新功能,我希望仅Happy Day更新标题Mary Ann

但我的sed功能也会Happy Day更新另一本书Mary Am

请告知我哪里做错了。

以下是我的编码

function update_book_info
{    
#Getting title from user 
echo "3) update_book_info"    
echo -n "Title: "
read title

while [[ -z "$title" ]] ; do
    echo -n "Please input title: "
    read title
done

#Getting author from user 
echo -n "Author: "
read author

while [[ -z "$author" ]] ; do
    echo -n "Title: "
    read author 
done

#If title and author from user input match the title and author field in BookDB.txt file 
if grep -i "^$title:$author" "BookDB.txt"; then 

    #then the program will display Book found and ask user to choice the next step
    echo -n "Book found!"
    echo ""
    echo ""
    echo "  a.) Update title"
    echo "  b.) Update Author"
    echo "  c.) Update Price"
    echo "  d.) Update Qty Avilable"
    echo "  e.) Update Qty Sold"
    echo "  f.) Back to main menu"
    echo ""
    echo -n "please choose an option: "
    read selection

#updating book title        
if [[ $selection == [Aa] ]]; then 
    echo ""
echo -n "Enter new title: "
read updatetitle 
    while [[ -z "$updatetitle" ]]; do
        echo -n "title: "
        read updatetitle
    done
sed -i "s/^${title}/${updatetitle}/" BookDB.txt
echo "Title updated!"

我还需要更新价格的建议。我收到了错误

3) update_book_info
   Title: Happy Day
   Author: Mary AM
   Happy Day:Mary Am:12.99:197:101
    Book found!

a.) Update title
b.) Update Author
c.) Update Price
d.) Update Qty Avilable
e.) Update Qty Sold
f.) Back to main menu

  please choose an option: c

  Enter new price: 123
  grep: Day:Mary: No such file or directory
  grep: AM: No such file or directory
  sed: -e expression #1, char 10: unterminated `s' command
  Price updated!

这是编码

elif [[ $selection == [Cc] ]]; then 
    echo ""
echo -n "Enter new price: "
    read updateprice

#if price is empty  
   while [ -z "$updateprice" ] ; do
       echo "Please input a price"
       read updateprice
    done
#if price is alphabate or not less than 0    
    while [[ "$updateprice" =~ ^[[:alpha:]]*$ ]] || [[ "$updateprice" < 0 ]]; do 
        echo "Please input number"
        echo -n "Price: "
        read updateprice 
    done
    price=`grep ${title}:${author} BookDB.txt | cut -d: -f3`
sed -i "s/${price}/${updateprice}/" BookDB.txt
echo "Price updated!"

0 个答案:

没有答案