在 shell 个脚本中查找多个字符串
Finding multiple strings in shell scripts
我正在尝试在给定文件中查找字符串 Error:
、Error :
、ERROR:
、ERROR :
,如果找到则转到 if 块如果找不到则转到其他块。
下面是我为执行此操作而编写的逻辑。
#!/bin/bash
file='file.log'
text=`cat $file`
echo $text
if [[ ${text} = *Error:* ||${text} = *ERROR:*|| ${text} = *ERROR :* || ${text} = *Error :* || $? -ne 0 ]]; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
似乎此逻辑有问题,因为它返回以下错误。
syntax error near `:*'
有人可以帮我解决这个问题吗?
使用 grep
更容易做到这一点,使用 -i
进行不区分大小写的匹配,使用 -q
抑制输出:
#!/bin/bash
file='file.log'
if grep -iq 'error \?:' "$file"; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
正则表达式error ?:
表示:文本error
,后跟一个可选的space(在space之后用\?
表示),接着通过 :
.
您要查找的模式很容易用正则表达式表示,因此您只需使用 grep
:
#!/bin/bash
file='file.log'
if grep -iq 'error \{0,1\}:' "${file}"
then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
无需将整个文件读入变量,也无需显式检查 $?
。
我正在尝试在给定文件中查找字符串 Error:
、Error :
、ERROR:
、ERROR :
,如果找到则转到 if 块如果找不到则转到其他块。
下面是我为执行此操作而编写的逻辑。
#!/bin/bash
file='file.log'
text=`cat $file`
echo $text
if [[ ${text} = *Error:* ||${text} = *ERROR:*|| ${text} = *ERROR :* || ${text} = *Error :* || $? -ne 0 ]]; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
似乎此逻辑有问题,因为它返回以下错误。
syntax error near `:*'
有人可以帮我解决这个问题吗?
使用 grep
更容易做到这一点,使用 -i
进行不区分大小写的匹配,使用 -q
抑制输出:
#!/bin/bash
file='file.log'
if grep -iq 'error \?:' "$file"; then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
正则表达式error ?:
表示:文本error
,后跟一个可选的space(在space之后用\?
表示),接着通过 :
.
您要查找的模式很容易用正则表达式表示,因此您只需使用 grep
:
#!/bin/bash
file='file.log'
if grep -iq 'error \{0,1\}:' "${file}"
then
STATUS=1
echo "=> string found."
else
echo "=> no string found."
fi
无需将整个文件读入变量,也无需显式检查 $?
。