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

2019-04-04 09:14发布

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.

标签: bash sed tail
5条回答
冷血范
2楼-- · 2019-04-04 09:26

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

查看更多
欢心
3楼-- · 2019-04-04 09:26
ruby -e 'a=File.readlines("file");puts a[-10..-1].join' > newfile
查看更多
\"骚年 ilove
4楼-- · 2019-04-04 09:28

Also you may use a variable:

LOG=$(tail -n 10 test.log)
echo "$LOG" > test.log
查看更多
劳资没心,怎么记你
5楼-- · 2019-04-04 09:34

You can do it using tempfile.

tail -n 10 test.log > test1.log

mv test1.log test.log
查看更多
一夜七次
6楼-- · 2019-04-04 09:41
echo "$(tail -n 10 test.log)" > test.log

Quotes are important. They preserve newline characters.

查看更多
登录 后发表回答