0

Question: How to delete all the files that are older than the latest modified file/s

The following one line command will find and delete all files except the latest 6 - but I am unable to figure out how to delete all files that are older than the latest file/s (there can be several latest files) -

ls -t | tail -n +6 | xargs rm --

Details: I would like to delete all the files that are older than the latest modified file date. It doesn't matter how many days it is older - as long as it is older than latest modified file, it needs to be deleted (100 days or 1000 days or 1 day or even 1 min older than the latest modified file).

Dir-
File 1 6/10/2019 9:40am
File 2 6/10/2019 9:37am
File 3 6/10/2019 9:40am
File 4 2/12/2019 12:39pm
File 5 7/01/2002 11:38pm

From this dir, after running the command, I should be able to only see File 1 and 3, all other files should be deleted regardless of how old those file are when compared the latest modified file/s.

sunskin
  • 1,620
  • 3
  • 25
  • 49
  • 1
    it would be nice if someone can comment when they downvote a question as it would help the OP understand whatever is wrong in the question – sunskin Jun 10 '19 at 13:53
  • I didn't downvote, but why should you only be able to see files 1 and 3 and not 2? – R4444 Jun 10 '19 at 13:55
  • File 2 is 9:37am which is older than File 1 & 3 are modified/added at 9:40am – sunskin Jun 10 '19 at 13:57
  • 1
    I did not downvote either but people here want to see what you've tried so far..Your post contains no code so I bet that is why it was downvoted... – GoinOff Jun 10 '19 at 13:58
  • 1
    Thanks @GoinOff, I will update my question. – sunskin Jun 10 '19 at 14:00

1 Answers1

2

The following should do:

newest=$(ls -Art | tail -n 1) && \
for f in *; do if [ "$f" -ot "$newest" ]; then rm -- "$f"; fi; done

Only restriction: newest file name must not contain newline.

This solution is not duplicate to Delete all files except the newest 3 in bash script because only using

tail -n

does not recognize if there are two or more newest files (with exactly the same modification time). That's why using

[ "$f" -ot "$newest" ]

here.

mirus
  • 78
  • 1
  • 5