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

喜夏-厌秋 提交于 2019-12-05 13:37:45

问题


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

tail -n 10 test.log

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

tail -n 10 test.log > test.log

doesn't work.


回答1:


You can do it using tempfile.

tail -n 10 test.log > test1.log

mv test1.log test.log



回答2:


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

Quotes are important. They preserve newline characters.




回答3:


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

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

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

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).




回答4:


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



回答5:


Also you may use a variable:

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


来源:https://stackoverflow.com/questions/3775383/how-can-i-remove-all-but-the-last-10-lines-from-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!