linux - 保留文件中最后 x 条日志 - Linux

标签 linux apache logging

我的服务器完全没有磁盘空间。我有一个非常非常大的日志文件,我需要保存日志文件的最后 10000 行。 我知道 tune2fs 有空间,但是日志文件很快就会填满,我不希望空间被用完,因为这会导致问题。

注意:最新的日志很重要,但文件的 95% 是无用信息。我正在修复,apache 日志报告的信息比我需要的多。

我不想创建一个新文件然后将日志移回。我想从文件中保存最后 X 条日志并删除其余日志而不先移动到新文件。

命令 我用过但不起作用:

cat test | tail -10000 | tee test

tail -n 10000 test | tee test

tail -n 10000 test > test

我还没有尝试过 sed,这可能有用吗?

如有任何建议,我们将不胜感激。此时我正在测试一个单独的文档文件,因为我现在不小心删除了所有日志。到目前为止,所有命令都失败了。 感谢您的帮助

附加说明:这现在纯属假设,因为我使用上述命令之一不小心破坏了我的文件。

最佳答案

您可以使用 dd 倒带覆盖原地的文件 搜索指针返回到输出文件的开头。例如 保留/tmp/a 的最后 5 行:

$ len=$(tail -5 /tmp/a | wc -c)
$ tail -5 /tmp/a | dd conv=notrunc of=/tmp/a
$ truncate -s $len /tmp/a

这是一个示例测试:

$ cat /var/log/messages >/tmp/a
$ wc -l /tmp/a
13160 /tmp/a
$ head -1 /tmp/a
Sep  2 03:34:11 pure-ftpd: [INFO] Timeout (no operation for 1800 seconds)
$ len=$(tail -5 /tmp/a | wc -c)
$ tail -5 /tmp/a | dd conv=notrunc of=/tmp/a ; truncate -s $len /tmp/a
$ wc -l /tmp/a
5 /tmp/a
$ cat /tmp/a
Sep  9 17:05:02 systemd: Started Session 7209 of user meuh.
Sep  9 17:10:01 systemd: Starting Session 7210 of user meuh.
Sep  9 17:10:01 systemd: Started Session 7210 of user meuh.
Sep  9 17:15:01 systemd: Starting Session 7211 of user meuh.
Sep  9 17:15:01 systemd: Started Session 7211 of user meuh.

关于linux - 保留文件中最后 x 条日志 - Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482887/

相关文章:

Linux 参数脚本

apache - Nutch - 作业失败 - 错误 mapred.FileOutputCommitter - Mkdirs 无法创建文件

entity-framework - 在 RavenDB 集合中存储/查询多种类型的最佳方法是什么?

java - Jetty Web 服务器拒绝在 Linux 上连接

javascript - <img src ='img.png'> 不显示本地文件( react )

java - 将 Apache 链接到具有多个域的 Tomcat

apache - Nutch 不会抓取表单中的所有链接

logging - 如何在 Elm 中记录调用图?

python - 带有参数 : avoid parenthesis when no arguments 的装饰器

linux - 如果用户存在 Ansible 则更新密码