Bash 编辑文件并保留最后 500 行
我希望创建一个 cron 作业,打开一个目录,循环遍历我创建的所有日志并删除所有行,但保留最后 500 行。
我正在考虑类似于
tail -n 500 filename > 的东西filename
这可行吗?
我也不知道如何在 bash 中循环访问目录。
I am looking to create a cron job that opens a directory loops through all the logs i have created and deletes all lines but keep the last 500 for example.
I was thinking of something along the lines of
tail -n 500 filename > filename
Would this work?
I also not sure how to loop through a directory in bash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果要截断的日志文件当前由某些服务打开,则按照前面的答案使用 mv 将中断这些服务。通过使用 cat 可以轻松克服这个问题:
If log file to be truncated is currently open by some services, then using mv as in previous answers will disrupt those services. This can be easily overcome by using cat instead:
考虑使用logrotate。
它不会执行您想要的操作(删除除最后 500 行之外的所有行),但它可以处理大于特定大小的日志文件(通常通过压缩旧日志文件并在某个时刻删除它们)。应该可以广泛使用。
Think about using logrotate.
It will not do what you want (delete all lines but the last 500), but it can take care of logfiles which are bigger than a certain size (normally by comressing the old ones and deleting them at some point). Should be widely available.
在我看来,最简单、最快的方法是使用变量:
In my opinion the easiest and fastest way is using a variable:
在 bash 中,您循环遍历目录中的文件,例如:
In bash you loop over files in a directory, e.g. like this: