如何使用grep这种情况?

时间:2014-01-31 11:09:59

标签: grep

grep功能无法正常工作。

这是我的代码:

echo -n "Title: "                        # prompt user for title
read title                               # get input from keyboard
echo -n "Author: "                       # prompt user for author
read author                              # get input from keyboard

if grep -q -i -w $title BookDB.txt       # check for title in BookDB.txt
  then                                     # if duplicate exist
    clear                                  # clear screen
    echo "Error! Book already exists!"     # prompt user about duplicated entry
    echo " "                               # newline
    continue                               # display main menu
  else                                     # if duplicate absent
    echo -n "Price: "                      # prompt user for price
    read price                             # get input from keyboard
    echo -n "Qty Available: "              # prompt user for qty available
    read qtyAvail                          # get input from keyboard
    echo -n "Qty Sold: "                   # prompt user for qty sold
    read qtySold                           # get input from keyboard

E.g

“指环王”在BookDB.txt

如果我想添加新书,将检查它是否存在。

然而,如果我想添加“石头之王”,它说已经存在了。 建议请。

2 个答案:

答案 0 :(得分:2)

始终引用您的shell变量:

if grep -q -i -w "$title" BookDB.txt

否则,shell将由空格分隔的每个部分解释为不同的参数。对于grep,这意味着在名为oftheStoneBookDB.txt的文件中搜索“Lord”。

答案 1 :(得分:0)

最小解决方案:

#!/bin/bash
echo -n "Title: "                        # prompt user for title
read title                               # get input from keyboard
if grep -q -i -w "$title" BookDB.txt ;  then 
   echo "Found"
else
   echo "do something else"
fi

尝试使用和不使用引用的$title来查看效果。

还要注意这将是部分匹配,所以“主”会找到“指环王”和“蝇王”。但是你面前有更大的问题......