问题
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