
我有以下日誌文件。我需要知道使用 shell 腳本是否有任何錯誤/可疑情況。
我需要找錯並檢查前面的單詞,如果它大於0,那麼DBA就有工作了。
Checking pubs2: Logical pagesize is 4096 bytes
DBCC CHECKSTORAGE for database 'pubs2' sequence 17 completed at Oct 21 2015 3:17PM. 4 faults and 0 suspect conditions were located. 0 checks were aborted. You should investigate the recorded faults, and plan a course of action that will correct them.
我已經在 Linux/Bash shell 中嘗試了以下命令,並且運作良好。
FLTCNT=`cat $MAILLOG | grep -oP '\S+(?=\s+faults and)'`
SPTCNT=`cat $MAILLOG | grep -oP '\S+(?=\s+suspect)'`
if [ $FLTCNT -gt 0 ] || [ $SPTCNT -gt 0 ] ; then
FAILED="Y"
# echo "Fault / suspect conditions found"
cat $MAILLOG >> $ERRLOG
fi
但是當我在 AIX 伺服器中執行相同的操作時,出現錯誤
grep: illegal option -- o
grep: illegal option -- P
usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
[-f pattern_file...] [file...]
usage: grep [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] [-e pattern_list...]
-f pattern_file... [file...]
答案1
假設您想要執行某些操作,如果檔案中存在兩個字串中的任何一個X faults
以及Y suspect
任何正整數值X
且不Y
等於。0
$MAILLOG
if grep -qwE '([1-9]|[0-9]{2,}) (faults|suspect)' "$MAILLOG"; then
# do something
fi
此模式([1-9]|[0-9]{2,})
將匹配大於零的單一數字,或任何具有兩位或更多位的數字。
該模式(faults|suspect)
將匹配字串faults
或suspect
。如果您也想包含checks
在那裡,只需使用(faults|suspect|checks)
.
-q
關閉grep
實用程式本來會產生的任何輸出非錯誤輸出的選項(我們只對 的退出狀態感興趣,grep
即它是否能夠匹配模式)。
該-w
選項使grep
執行“單字搜尋”。在這種情況下,這意味著它將查找10 faults
而不是子字串,0 faults
因為 中的零10
不會開始一個新的“單字”,但它會開始一個新的“1
單字”。這也意味著該字串2 faultsmen
(無論該字串不太可能)不會觸發匹配。
需要-E
支援使用交替 ( |
) 的擴展正規表示式。
答案2
您可以嘗試使用 grep:
grep -c "your word to match" /log/file
例如:
$ grep -c "upgraded" /var/log/pacman.log
244