Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete oldest file for each directory in a tree

I have a directory tree like the following:

Games
-- Game1
  -- file1
  -- file2
  -- file3
-- Game2
  -- file1
  -- file2
-- GameN
  -- filen

And I would like to delete the oldest file for each Game subdirectory.

Tried searching for the various questions already posted but didn’t find a solution.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

If the files not containing special characters, like \n (no problem with files with spaces):

for dir in Games/Game*/; do
    (
        cd "$dir"
        echo rm "$(\ls -tr | sed q)"
    )
done

This is the only one case where I parse ls

Drop echo command if your attempts are satisfactory.

  • ls -tr sort files by date of modification in reverse order.
  • sed q take the first line
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading