Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

tail

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.

like image 641
sbrink Avatar asked Sep 23 '10 04:09

sbrink


People also ask

How do you keep only the last n lines of a log file?

To do this as cleanly as possible, first move the existing log file to a temporary location. Then combine it with the previously saved archive file, and keep up to n lines. As for the process which is logging, it should just start a new file the next time it writes a log message. Save this answer.

Which command extract the bottom 10 lines from a file by default?

Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates. Example 1: By default “tail” prints the last 10 lines of a file, then exits.

Which command can delete a range of lines from a file?

The sed command can remove the lines of any range. For this, we just have to enter 'minimum' and 'maximum' line numbers. In this example, we will remove the lines ranging from 4 to 7 numbers. After removing these ranges of lines, our file will look like this.

How can you view the last 15 lines of the file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.


2 Answers

You can do it using tempfile.

tail -n 10 test.log > test1.log

mv test1.log test.log
like image 158
Ankit Bansal Avatar answered Oct 12 '22 04:10

Ankit Bansal


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

Quotes are important. They preserve newline characters.

like image 42
Inna Avatar answered Oct 12 '22 02:10

Inna