Home > front end >  Delete oldest file for each directory in a tree
Delete oldest file for each directory in a tree

Time:01-08

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.

Thanks

CodePudding user response:

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
  • Related