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

Get the last non-empty string from a file using shellscript

我写了下面的代码:

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 中搜索最后一个非空行,而不考虑插入的空行数?

awk 来拯救!

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

如果你的日志太长,先从宽大的尾巴开始

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

将打印最后 non-empty 行。