简体   繁体   English

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

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

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. 提供正确的结果,但我不知道如何修改test.log本身。 And

tail -n 10 test.log > test.log

doesn't work. 不起作用。

You can do it using tempfile. 您可以使用tempfile来完成。

tail -n 10 test.log > test1.log

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

Quotes are important. 行情很重要。 They preserve newline characters. 它们保留换行符。

Also you may use a variable: 您也可以使用变量:

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

Invoke ed command (text editor): 调用命令(文本编辑器):

 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')。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM