使用shellscript从文件中获取最后一个非空字符串

时间:2015-09-30 19:26:27

标签: unix awk sed blank-line

我写了以下代码:

success="Traffic Engineering Tunnel validated successfully"
text=$(tail -2 /apps/pofitb/logs/tunnels.log)
echo $executed_date
if  [[ $text = $success ]]
then
    text=$(tail -2 /apps/pofitb/logs/tunnels.log)
    echo "Tunnel script execution is successful" | mailx -s "Tunnel script is executed succefsfully on $executed_date" abc@gmail.com 
else
    echo "Tunnel script  lastly executed  on $executed_date" | mailx -s "Tunnel script  FAILED!!!" abc@gmail.com 
fi
exit

目前,tunnel.log文件在更新时有空行。因此,text=$(tail -2 /apps/pofitb/logs/tunnels.log)从文件末尾提取最后一个非空行。如果在文件末尾插入的空行数为1,则此方法有效。

如何修改脚本,以便脚本从文件tunnel.log中搜索最后一个非空白行,而不管插入的空白行数是多少?

1 个答案:

答案 0 :(得分:2)

要求救援!

tac log | awk 'NF{print;exit}'

如果您的日志太长,请先从慷慨的尾巴开始

 tail -5 log | tac | awk 'NF{print;exit}'

将打印最后一个非空行。