2015-01-09 46 views
0

我想做一個代碼,提示用戶輸入一本書的標題和作者,我想使用grep來獲取基於標題和作者的數據並回顯爲用戶可以查看和編輯的價格,而無需用戶輸入舊價格linux腳本來更新價格

我需要在試圖獲得$價格變量的幫助就可以通過輸入標題和作者

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

你寫的腳本有什麼問題? – Barmar

+1

您的'grep'命令使用'$ price',但是您從不設置該變量。 – Barmar

+0

那麼,我應該如何修改它,以便我可以得到我需要的變量? – Ken

回答

1

關於上述問題,我想出了一個答案。希望它可以幫助

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

} 
+0

它幫助我感謝:D – Ken

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

對不起,我想問什麼= $做?爲什麼-F:-v?不熟悉awk – Ken

+0

'$(command)'執行該命令並替換其輸出;這是基本的shell腳本語法。 '-F:'將字段分隔符設置爲':'而不是'awk'中的空格(它在文檔中)。 – Barmar

+0

嗨,我用價格的線,但它沒有迴應舊價格,而是隻是去了新的價格 – Ken