Search code examples
bashsortingpipewc

Always keep n newest files in dir


I'm trying to create a one-liner which should remove excess files from dir to save it from consuming too much space.

ls -r --sort=time | head -${{ls | wc -l} - n} | xargs rm -f

n should stand for number of files I want to keep in directory.

I'm doing something wrong here and can't figure out what. Can someone help please?


Solution

  • ( ls -t | head -n 25 ; ls ) | sort | uniq -u | sed -e 's,.*,"&",g' | xargs rm
    

    Done the trick for me.

    Delete all but the most recent X files in bash <-- here

    Thanks for reply.