Linux 4 All

Best Linux tricks source

Some time ago I had to deal with a request to delete all but the newest 50 files from a folder. To make my life a little bit miserable, there were other folders inside that folder which shouldn’t be deleted and obviously some files with space in their names

In the end I did a small script taking the folder as first parameter and number of files to keep as the second one.

#!/bin/bash
if [ $# -eq 0 ]
 then
  echo " This script will delete all but newest files from a specified folder."
  echo ""
  echo " Usage: source $0  "
  exit 1
fi

TOTAL_FILES=$(find $1 -maxdepth 1 -type f -print0| xargs -0 ls -lt | wc -l)
FILES_TO_DELETE=$(echo "$TOTAL_FILES-$2" | bc)

find $1 -maxdepth 1 -type f -print0 | xargs -0 ls -t | tail -$FILES_TO_DELETE | sed -e 's/ /\\ /g' | xargs rm

Nice and useful curl output arrow-right
Next post

arrow-left rm -rf is gone
Previous post

Leave a Reply

Your email address will not be published. Required fields are marked *