我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
当前回答
试试这个:
if [[ $(grep "SomeString" $File) ]] ; then
echo "Found"
else
echo "Not Found"
fi
其他回答
最短(正确)版本:
grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"
也可以写成
grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"
但在这种情况下,你不需要显式地测试它,所以对:
grep -q "something" file && echo "yes" || echo "no"
试试这个:
if [[ $(grep "SomeString" $File) ]] ; then
echo "Found"
else
echo "Not Found"
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"
我这样做了,似乎还不错
if grep $SearchTerm $FileToSearch; then
echo "$SearchTerm found OK"
else
echo "$SearchTerm not found"
fi
如果您想检查文件是否不包含特定的字符串,您可以按照以下方法进行检查。
if ! grep -q SomeString "$File"; then
Some Actions # SomeString was not found
fi