我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:

 if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi

我的代码出了什么问题?


当前回答

如果您想检查文件是否不包含特定的字符串,您可以按照以下方法进行检查。

if ! grep -q SomeString "$File"; then
  Some Actions # SomeString was not found
fi

其他回答

##To check for a particular  string in a file

cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME  
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi
if grep -q [string] [filename]
then
    [whatever action]
fi

例子

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi
grep -q [PATTERN] [FILE] && echo $?

如果找到模式,则退出状态为0 (true);否则blankstring。

试试这个:

if [[ $(grep "SomeString" $File) ]] ; then
   echo "Found"
else
   echo "Not Found"
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"