如何连续tail -f
记录日志、查找所有文件 ( sed
) 并显示 ( cat
) 找到的文件
审计日志中的示例数据。
tail -f /var/log/httpd/modsec_audit.log | sed 's/[^\/]*/\./;s/].*$//g'
输出
./apache/20180508/20180508-1428/20180508-142802-WvH6QgoeANwAAMwsFZ4AAAAF
./apache/20180508/20180508-1428/20180508-142803-WvH6QgoeANwAAMwtFfcAAAAG
./apache/20180508/20180508-1428/20180508-142803-WvH6QwoeANwAAMwuFlUAAAAH
./apache/20180508/20180508-1513/20180508-151357-WvIFBQoeANwAAMwnE@4AAAAA
./apache/20180508/20180508-1513/20180508-151357-WvIFBQoeANwAAMwoFD8AAAAB
./apache/20180508/20180508-1516/20180508-151608-WvIFiAoeANwAAMz1FSwAAAAA
./apache/20180508/20180508-1516/20180508-151609-WvIFiQoeANwAAMz2FYIAAAAB
./apache/20180508/20180508-1516/20180508-151611-WvIFiwoeANwAAMz3FeEAAAAC
./apache/20180508/20180508-1516/20180508-151611-WvIFiwoeANwAAMz4Fj4AAAAD
./apache/20180508/20180508-2112/20180508-211205-WvJY9QoeANwAAM1MFCoAAAAA
与回声一起工作
echo "./apache/20180508/20180508-1428/20180508-142802-WvH6QgoeANwAAMwsFZ4AAAAF" | sed 's/[^\/]*/\./;s/].*$//g' | awk '{print $0}' | xargs cat
与猫一起工作
cat /var/log/httpd/modsec_audit.log | sed 's/[^\/]*/\./;s/].*$//g' | awk '{print $0}' | xargs cat
不适用于尾巴...
tail -f /var/log/httpd/modsec_audit.log | sed 's/[^\/]*/\./;s/].*$//g' | awk '{print $0}' | xargs cat
我认为拖尾不起作用,因为脚本永远不会终止,并且sed
仍在缓存结果,直到脚本终止。
有没有办法让这项工作持续进行?
答案1
缓冲正在成为障碍。
使用while read line
shell 中的 a ,它应该逐行读取并避免大多数缓冲问题:
tail -f /var/log/httpd/modsec_audit.log | while read line; do
echo "$line" | sed 's/[^\/]*/\./;s/].*$//g' | awk '{print $0}' | xargs cat
done
尽管您可能可以做得更好,也可以使用 shell (bash) 来匹配日志行中的文件名:
tail -f /var/log/httpd/modsec_audit.log | while read line; do
line=${line/*([^\/])/.}
line=${line%]*}
[[ -n "${line}" ]] && cat "${line}"
done
答案2
试试这个:
tail -f /var/log/httpd/modsec_audit.log | stdbuf -oL sed 's/[^\/]*/\./;s/].*$//g' | stdbuf -oL awk '{print $0}' | while IFS='' read -r file; do cat $file ; done