bash 如何从文件中删除除最后 10 行之外的所有内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3775383/
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:40:25  来源:igfitidea点击:

How can I remove all but the last 10 lines from a file?

bashsedtail

提问by sbrink

Is it possible to keep only the last 10 lines of a lines with a simple shell command?

是否可以使用简单的 shell 命令仅保留一行的最后 10 行?

tail -n 10 test.log

delivers the right result, but I don't know how to modify test.log itself. And

提供正确的结果,但我不知道如何修改 test.log 本身。和

tail -n 10 test.log > test.log

doesn't work.

不起作用。

回答by Ankit Bansal

You can do it using tempfile.

您可以使用临时文件来完成。

tail -n 10 test.log > test1.log

mv test1.log test.log

回答by Inna

echo "$(tail -n 10 test.log)" > test.log

Quotes are important. They preserve newline characters.

报价很重要。它们保留换行符。

回答by hluk

Invoke ed command (text editor):

调用 ed 命令(文本编辑器):

 echo -e '1,-10d\nwq' | ed <filename>

This will send command to delete lines ('1,-10d'), save file ('w') and exit ('q').

这将发送命令来删除行 ('1,-10d')、保存文件 ('w') 和退出 ('q')。

Also note that ed fails (return code is 1) when the input file has less than 11 lines.

另请注意,当输入文件少于 11 行时,ed 会失败(返回码为 1)。

Edit:You can also use vi editor (or ex command):

编辑:您也可以使用 vi 编辑器(或 ex 命令):

vi - +'1,-10d|wq' <filename>

But if the input file has 10 or less lines vi editor will stay opened and you must type ':q' to exit (or 'q' with ex command).

但是,如果输入文件有 10 行或更少行,vi 编辑器将保持打开状态,您必须输入 ':q' 退出(或使用 ex 命令输入 'q')。

回答by ghostdog74

ruby -e 'a=File.readlines("file");puts a[-10..-1].join' > newfile

回答by David

Also you may use a variable:

你也可以使用一个变量:

LOG=$(tail -n 10 test.log)
echo "$LOG" > test.log