我正在嘗試在給定檔案中查找字串Error:, Error :, ERROR:,ERROR :如果找到則轉到 if 塊如果未找到則轉到 else 塊。
以下是我為執行此操作而撰寫的邏輯。
#!/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 `:*'
有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
您正在尋找的模式很容易用正則運算式表示,因此您可以使用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
無需將整個檔案讀入變數,也無需$?顯式檢查。
uj5u.com熱心網友回復:
這更容易使用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,后跟一個可選的空格(由?空格后的a表示),然后是:。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/471549.html
上一篇:帶sed的while回圈
