Bash脚本提取Cognos日志指定时间戳后错误码失败求助
Cognos Configuration日志错误码提取问题解决
日志示例
29/08/2023,11:26:42,Info,========== Cognos Configuration ========= SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/opt/sw/cognos/analytics/bin/slf4j-nop-1.7.23.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/opt/sw/cognos/analytics/configuration/utilities/config-util.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory] 29/08/2023,11:26:48,Info, Silent exit with error code: 0
需求说明
- 定位含
Cognos Configuration的日志行(作为日志启动标识) - 提取该行之后,第二个带时间戳行中的错误码
X - 错误码为0判定启停成功,非0判定失败
原命令失效原因
原命令sed -n "/$(date +'%d/%b/%Y')/,/*/p" cogconfig.log |grep -i "with error code:"无法获取错误码,问题出在:
- 日期格式不匹配:日志使用
dd/mm/yyyy格式,但date +'%d/%b/%Y'输出的是dd/英文月份缩写/yyyy(如29/Aug/2023),完全匹配不到日志行 - sed范围表达式错误:
/*/是无效的正则表达式,无法正确界定需要提取的日志范围
解决方案
方案1:用awk精准提取(推荐)
awk可以直接按逻辑匹配启动行后定位错误码行,效率更高:
exit_code=$(awk -F, '/Cognos Configuration/{flag=1} flag && /Silent exit with error code:/{print $NF; exit}' cogconfig.log)
-F,:以逗号作为字段分隔符/Cognos Configuration/{flag=1}:匹配到启动标识行后,开启后续匹配开关flag && /Silent exit with error code:/:开关开启后,匹配错误码行print $NF:打印该行最后一个字段(即错误码)exit:找到目标行后立即退出,避免遍历整个日志
方案2:修正sed+grep组合命令
先生成和日志一致的日期格式,再用sed限定日志范围:
today=$(date +'%d/%m/%Y') exit_code=$(sed -n "/$today.*Cognos Configuration/,/$today.*Silent exit with error code:/p" cogconfig.log | grep -oE 'error code: [0-9]+' | awk '{print $NF}')
today=$(date +'%d/%m/%Y'):生成dd/mm/yyyy格式的当日日期- sed范围匹配:从当日的启动标识行到当日的错误码行
- grep提取:用正则匹配错误码部分,awk提取数字
结果判定
提取到错误码后,可通过如下逻辑判断启停状态:
if [ "$exit_code" -eq 0 ]; then echo "Cognos 启停成功" else echo "Cognos 启停失败,错误码:$exit_code" fi
内容的提问来源于stack exchange,提问作者Champakram
相关产品推荐
相关产品推荐

