Bash 编辑文件并保留最后 500 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2880819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:07:05  来源:igfitidea点击:

Bash edit file and keep last 500 lines

bashloggingtail

提问by Lizard

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.

我正在寻找创建一个 cron 作业,它打开一个目录循环遍历我创建的所有日志并删除所有行,但例如保留最后 500 行。

I was thinking of something along the lines of

我在想一些事情

tail -n 500 filename > filename

tail -n 500 filename > filename

Would this work?

这行得通吗?

I also not sure how to loop through a directory in bash.

我也不知道如何在 bash 中遍历目录。

采纳答案by tanascius

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.

考虑使用logrotate
它不会执行您想要的操作(删除除最后 500 行之外的所有行),但它可以处理大于特定大小的日志文件(通常通过压缩旧文件并在某个时候删除它们)。应该可以广泛使用。

回答by user2553977

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:

如果要截断的日志文件当前由某些服务打开,则在先前的答案中使用 mv 将中断这些服务。这可以通过使用 cat 来轻松克服:

tail -n 1000 myfile.log > myfile.tmp
cat myfile.tmp > myfile.log

回答by TheFax

In my opinion the easiest and fastest way is using a variable:

在我看来,最简单快捷的方法是使用变量:

LASTDATA=$(tail -n 500 filename)
echo "${LASTDATA}" > filename

回答by Paul R

DIR=/path/to/my/dir # log directory
TMP=/tmp/tmp.log # temporary file
for f in `find ${DIR} -type f -depth 1 -name \*.log` ; do
  tail -n 500 $f > /tmp/tmp.log
  mv /tmp/tmp.log $f
done

回答by miku

In bash you loop over files in a directory, e.g. like this:

在 bash 中,您可以遍历目录中的文件,例如:

cd target/directory

for filename in *log; do
    echo "Cutting file $filename"
    tail -n 500 $filename > $filename.cut
    mv $filename.cut $filename
done