15

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.

martin clayton
  • 76,436
  • 32
  • 213
  • 198
  • 3
    as a rule of thumb, never use a file simultaneously as input and output, you never know how it will end up. – tokland Sep 23 '10 at 14:48
  • 1
    Good advice. I just did `tail -n 10 test.log > test.log` and ended up with nothing (a blank file). – kgf3JfUtW Jan 16 '18 at 16:37

6 Answers6

19

You can do it using tempfile.

tail -n 10 test.log > test1.log

mv test1.log test.log
Ankit Bansal
  • 4,962
  • 1
  • 23
  • 40
  • 2
    This works, thank you. However, **do NOT forget the `1`** because I did `tail -n 10 test.log > test.log` and am left with a blank file! – kgf3JfUtW Jan 16 '18 at 16:36
15
echo "$(tail -n 10 test.log)" > test.log

Quotes are important. They preserve newline characters.

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
Inna
  • 151
  • 1
  • 2
2

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

hluk
  • 5,848
  • 2
  • 21
  • 19
  • Odd not to see this answer being liked more. It’s elegant and also does the job on BSD rather than just Linux. Thanks! – Xen Jul 31 '20 at 07:17
1

Also you may use a variable:

LOG=$(tail -n 10 test.log)
echo "$LOG" > test.log
David
  • 2,942
  • 33
  • 16
1
ruby -e 'a=File.readlines("file");puts a[-10..-1].join' > newfile
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

I know this is old, but I wanted to demonstrate how process substitution can also help here:

cp <(tail -n 10 test.log) test.log

As process substitution results in a temporary file it doesn't overwrite test.log too soon. That's in contrast to the attempt in the question.

sjngm
  • 12,423
  • 14
  • 84
  • 114