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

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

329,我目前正在编写一个 bash 脚本,用于检查中是否存在确切的字符串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启用扩展正则表达式,然后匹配任何一个后跟329逗号 ( 329,) 或329位于行尾的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

问候

相关内容