shell: delete the last line of a huge text log file [duplicate]

和自甴很熟 提交于 2019-11-30 13:03:18

问题


I asked a question regarding popping the last line of a text file in PHP, and now, is it possible to re-write the logic in shell script?

I tried this to obtain the last line:

tail -n 1 my_log_file.log

but I am not sure how can I remove the last line and save the file.

P.S. given that I use Ubuntu server.


回答1:


(Solution is based on sch's answer so credit should go to him/her)

This approach will allow you to efficiently retrieve the last line of the file and truncate the file to remove that line. This can better deal with large inputs as the file is not read sequentially.

# retrieve last line from file
LAST=$(tail -n 1 my_log_file.log)

# truncate file
let TRUNCATE_SIZE="${#LAST} + 1"
truncate -s -"$TRUNCATE_SIZE" my_log_file.log

# ... $LAST contains 'popped' last line

Note that this will not work as expected if the file is modified between the calls to tail and truncate.




回答2:


To get the file content without the last line, you can use

head -n-1 logfile.log

(I am not sure this is supported everywhere)

or

sed '$d' logfile.log



回答3:


What you want is truncate the file just before the last line without having to read the file entirely.

truncate -s -"$(tail -n1 file | wc -c)" file

That's assuming the file is not currently being written to.

truncate is part of the GNU coreutils (so generally found on recent Linux distributions) and is not a standardized Unix or POSIX command. Many "dd" implementations can be used to truncate a file as well.




回答4:


One way is:

sed '$d' < f1 > f2 ; mv f2 f1


来源:https://stackoverflow.com/questions/12176492/shell-delete-the-last-line-of-a-huge-text-log-file

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