如何檢查文件中是否存在字串

如何檢查文件中是否存在字串

我目前正在編寫一個 bash 腳本,該腳本應該329,檢查myfile.我在網上搜索並找到了一些答案,但我無法使用-x參數,因為我的數字比329,上的數字多myfile。如果沒有-x參數,我也可以獲得Exists結果329,這是我不想要的。

我試過;

if grep -xqFe "329," "myfile"; then
    echo -e "Exists"
else
    echo -e "Not Exists"
fi

輸出是;

Not Exists

代替myfile;

329, 2, 57

我該如何解決這個問題?

答案1

此處-x不相關。這意味著(來自man grep):

-x, --line-regexp
       Select  only  those  matches that exactly match the whole line.
       For a regular expression pattern, this is  like  parenthesizing
       the pattern and then surrounding it with ^ and $.

因此,只有當您想要查找僅包含您要查找的確切字串的行時,它才有用。您想要的選項是-w

-w, --word-regexp
       Select  only  those  lines  containing  matches that form whole
       words.  The test is that the matching substring must either  be
       at  the  beginning  of  the  line,  or  preceded  by a non-word
       constituent character.  Similarly, it must be either at the end
       of  the  line  or followed by a non-word constituent character.
       Word-constituent  characters  are  letters,  digits,  and   the
       underscore.  This option has no effect if -x is also specified.

如果您發現目標字串是一個獨立的“單字”,即被“非單字”字元包圍的字串,那麼它將匹配。你也不需要這裡-F,只有當你的模式包含在正則表達式中具有特殊含義的字符時才有用,你想從字面上找到這些字符(例如*),並且你根本不需要-e,如果你想要的話,這將是需要的給予不只一種模式。所以您正在尋找:

if grep -wq "329," myfile; then 
    echo "Exists" 
else 
    echo "Does not exist"
fi

,如果您還想在數字是行中最後一個數字時進行匹配,因此後面沒有數字,您可以使用grep -E啟用擴展正則表達式,然後進行匹配任何一個a329後面跟著逗號 ( 329,) 或329位於行尾的 a ( 329$)。您可以像這樣組合它們:

if grep -Ewq "329(,|$)" myfile; then 
    echo "Exists" 
else 
    echo "Does not exist"
fi

答案2

另一個選擇可能是:

if cat myfile | tr "," "\n" | grep -xqF "329"; then
    echo -e "Exists"
else
    echo -e "Not Exists"
fi

問候

相關內容