删除日志文件中较旧的日志

删除日志文件中较旧的日志

两年以来,我每天都会附加多个日志文件,想要清理每个日志文件中超过 90 天的日志。我可以包含过去几年的日期吗?比如 90..1000 删除超过 3 个月到过去几年的文件?

答案1

手动管理日志文件很复杂。您的日志文件是如何使用的?它是定期更新还是长时间运行的进程(守护进程)会不断打开它?如果是后者,您将必须对守护进程执行某些操作(发出信号或重新启动)。阅读man守护进程的页面。

当日志文件 ( big.log) 未由任何进程打开时(通过 检查sudo lsof $PWD/big.log),请使用带有“ ”和“ ”格式化选项的date命令 ( man date)以与 中使用的格式相同的格式生成 90 天前的日志文件。--date="today - 90 days"+big.log

# Warning: bash pseudo-code due to fuzziness of spec
# Warning: run any derived code through https://shellcheck.net
# **UNTESTED**
# You: Backup big.log, Just In Case

longago="$(date --date="today - 90 days" +"%...")"
# find the line number of the first occurence of the long ago date. 
# only want the 1st match, 
# only want the line number (up to the colon)
firstkeep="$(grep -n "$longago" big.log | head -n1 | cut -d: -f1)"
# left as an exercise: what if there are no logs on $longago?
# simple check? 
[[ -z "$firstkeep" ]] && \
    error ...
# now, just keep from $firstkeep to the end
tail -n "$firstkeep" big.log
 >small.log

# now, check small.log (add tests)
wc -l big.log small.log

# when you're satisfied with small.log

# If the first mv works, do the second
mv big.log big.log.old && mv small.log big.log

# finally, when you're satisfied with the new, smaller big.log.
df.;rm big.log.old;df .

所有这些命令都有man页面。根据需要阅读它们man bash

相关内容