在shell scipt上需要一些帮助(使用grep命令)

时间:2016-01-27 14:27:12

标签: linux shell sh

我有一个日志文件,我正在尝试编写一个shell脚本来查找多行文件中的多个字符串。

例如,如果我看到短语" class = com.comcast.parker.GetCurrentAudioLanguageResponse"和"状态:好的"在日志中,我应该打印getAudioLanguage SUCCESSFUL,否则getAudioLanguage FAILED。所以我的shell脚本是这样的:

脚本文件:

logfile=$1

if grep "{\"class\":\"com.comcast.parker.GetCurrentAudioLanguageResponse\"" jags.txt | grep "{\"status\":\"OK\"" | wc -l ; then
    echo "getAudioLanguage SUCCESSFUL"
fi
if grep "{\"class\":\"com.comcast.parker.GetCurrentAudioLanguageResponse\"" $logfile | grep -q "GENERAL_ERROR" | wc -l ; then
    echo "getAudioLanguage FAILED"
fi

在日志中,我获得状态为GENERAL_ERROR,因此它应该打印FAILED,但输出显示为getAudioLanguage SUCCESSFUL ..

对此有何帮助?

日志文件:

160125-11:11:28.442500 [mod=SYS, lvl=INFO] [tid=2332] ======= Message is onRPCCall ======>
160125-11:11:28.442614 [mod=SYS, lvl=INFO] [tid=2332] Entering onRPCCallEvent for request ---> getAudioLanguage
160125-11:11:28.442845 [mod=SYS, lvl=INFO] [tid=2332] Received json request = {"event":1,"handler":1,"name":"onRPCCall","params":{"callGUID":"d75a5bab-6b29-4ab4-9f7e-3cf32d4a05b1","callParams":[{"getAudioLanguage":{}}],"class":"com.comcast.xre.events.XRERPCCallInfo","destinationSessionGUID":"ab00ebea-5f63-4619-9877-273a2bceea1d","method":"getAudioLanguage","sourceSessionGUID":"ab00ebea-5f63-4619-9877-273a2bceea1d"},"phase":"STANDARD","source":1}

160125-11:11:28.442920 [mod=SYS, lvl=INFO] [tid=2332] GetCurrentAudioLanguage : Entered
160125-11:11:28.442968 [mod=SYS, lvl=INFO] [tid=2332] pMainPlayer is NULL.
160125-11:11:28.443012 [mod=SYS, lvl=INFO] [tid=2332] getAudioLanguage: Get Audio Language returned ��v`>       T�=     T0~�t
160125-11:11:28.443676 [mod=SYS, lvl=INFO] [tid=2332] ====== Response sending is {"appId":1,"command":"CALL","commandIndex":5,"method":"generateAppEvent","params":[{"class":"com.comcast.xre.events.XREOutgoingEvent","name":"onRPCReturn","params":{"callGUID":"d75a5bab-6b29-4ab4-9f7e-3cf32d4a05b1","class":"com.comcast.xre.events.XRERPCReturnInfo","destinationSessionGUID":"ab00ebea-5f63-4619-9877-273a2bceea1d","method":"getAudioLanguage","returnVal":{"class":"com.comcast.parker.GetCurrentAudioLanguageResponse","status":"GENERAL_ERROR","statusMessage":"Getting Current Audio Language was unsuccessful."},"sourceSessionGUID":"ab00ebea-5f63-4619-9877-273a2bceea1d"}},"ab00ebea-5f63-4619-9877-273a2bceea1d"],"targetId":1,"targetPath":"","timestamp":0}

2 个答案:

答案 0 :(得分:1)

假设您的搜索模式编写正确,那么您可以使用以下内容:

if grep pattern_one file | grep -q pattern_two; then
    echo "getAudioLanguage SUCCESSFUL"
fi

这会过滤第一个模式的输出并使用grep -q,其退出状态指示第二个模式是否也匹配。

那就是说,有点像你试图解析JSON。如果可能的话,最好使用jq之类的东西。

答案 1 :(得分:0)

您可以使用单个grep来执行此操作,而不是多个awk

awk '/{"class":"com\.comcast\.parker\.GetCurrentAudioLanguageResponse"/{
   exit ($0 !~ /"status":"GENERAL_ERROR"/)}' file && echo "getAudioLanguage FAILED"

awk '/{"class":"com\.comcast\.parker\.GetCurrentAudioLanguageResponse"/{
   exit ($0 !~ /"status":"OK"/)}' file && echo "getAudioLanguage SUCCESSFUL"