Delete the last X files using sed

Simple sed trick - keeping the last X files

How would you remove all but the last 10 files in a directory?

So let’s create 15 files with one second between there creation time. Oldest one (first one) will be called 1.file and the newest one (last one) will be called 15.file

Run this code to do that:

for i in `seq 1 15`; do
  touch $i.fil
  sleep 1

What this does is runs seq 1 15 in a shell first and substitutes its output into a list which the variable “i” will iterate through. The touch $i.file command will create an empty file from the list of numbers giving us 15 different empty files from 1.file to 15.file.

Now the trick - to save the latest 5 files we really want to remove every file other than the last five (ie 1.file, 2.file …, 10.file) thus leaving 11.file - 15.file alone.

ls -lt # shows all the files in time order - most recent is at the top. # BUT BE AWARE there is total number of listed files printed first

So we want a list of file not including the top 5 and not the printed total number of files. What’s more is we ONLY want the file name not the entire long listing (with permissions, ownership, size, date, and name).

ls -t # gives all the files in time order with only the file names

Now lets delete the top 5 + the total line from this list ls -t | sed “1,6d”

We are almost there… To use that list and remove the files ….. wait…. lets be safe and double check what we are about to do. Rather than running the rm command, let’s echo the rm command. Here is the test run code

echo rm $(ls -t | sed "1,6d")

What is within the $(....) will get executed by the shell first placing its output into the full command before running it. I could have used backticks instead of the $(….).

Hopefully you will see the following echoed to your screen:

rm 9.file 8.file 7.file 6.file 5.file 4.file 3.file 2.file 1.file

That looks like the command we want so now you can run it without the echo :

rm $(ls -t | sed "1,6d") # this one will actually remove all but the latest 5 files