Remove all but newest file from all sub directories

45 views Asked by At

I have found the following which will list the files in all subdirectories, hide the last 5, and then delete the rest:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -5 | xargs rm

Unfortunately if I don't know how many subdirectories there are, it won't delete the correct number of files. Does anyone have a way to transverse each directory, and then delete all but the newest of file in each subdirectory?

Directory structure would be the following:

-> Base Directory -> Parent Directory -> Child directory

2

There are 2 answers

0
GuBo On

I'd write a script.

It would be a recursive function:

  • call function: rm_files(base_dir)
  • list all directories
  • if there are directories go through on the list and call rm_files(act_dir) for each item
  • else (if there is no directories):
    • list all files
    • delete all files but the newest
  • return from function

In case lot of subdirectories it may be memory problem because of the recursive function.

0
cycloxr On

I found I was able to do what I needed to do with the following one liner:

find . -name *.* -mmin +59 -delete > /dev/null