0

I have changed this post down to just what I think the main problem is..

There is a need to leave the two latest how to delete all files except the latest three in a folder

ls -t1 /home/jdoe/checks/downloads/*.md5 | head -n +2 | xargs rm -r

This removes the oldest files..

And to test:

ls -t1 /home/jdoe/checks/downloads/*.md5 | head -n +2

We really want to leave the two (2) newest files:

ls -t1 /home/jdoe/checks/downloads/*.md5 | tail -n +2 | xargs rm -r

This does not seem to work..

And to test:

ls -t1 /home/jdoe/checks/downloads/*.md5 | tail -n +2

Thanks!

Community
  • 1
  • 1
Leptonator
  • 3,379
  • 2
  • 38
  • 51
  • I can't find a Q, interesting as your back-story is ;-) Maybe you want to highlight something like 'Why is X happening' OR 'How do we do Y' at the top, then we can read the backstory if needed. Actually, you should probably re-read http://stackoverflow.com/help/mcve` and whittle the above down to just the current issue. Good Luck! – shellter Mar 10 '16 at 16:03
  • @shellter I have changed the formatting of the question to be what I think the main problem is at this point. – Leptonator Mar 15 '16 at 14:47
  • arg! you wrote "leave the two latest how to delete all files except the latest three in a folder". Disregarding two or three, you want to be able to leave the N newest files in a directory, and delete all others? – shellter Mar 15 '16 at 15:37
  • @shellter I apologize for confusing question, but yes I want to leave the two (2) newest files. – Leptonator Mar 15 '16 at 15:41
  • ok, no worries. I have something else, I'll be back in a little while (less than 1 hr I think). Good luck. – shellter Mar 15 '16 at 16:01

1 Answers1

1

I was able to get some assistance from one of my co-workers and this appears to be what we need.

   ls -1tr /home/jdoe/checks/downloads/*.md5 | head -n -2 | while read f; do
     #rm -f "$f"
     print "file to delete is $f"
   done
Leptonator
  • 3,379
  • 2
  • 38
  • 51