Last Updated: September 30, 2021
·
414
· jamesduncombe

Remove all files in current directory other than x day

** PLEASE be careful before running the following commands, make sure you fully understand whats going on **

Say you'd like to remove all files in a directory other than those created on a certain day of the week...

ls -l --time-style='+%a' | awk '$6 != "Fri"' | grep -v total

The output from the above command will show all files that were not created on a Friday.

To remove them, add xargs into the mix:

PLEASE be careful here - make sure you know whats going on before running this...

ls -l --time-style='+%a' | awk '$6 != "Fri" { print $7 }' | grep -v total | xargs rm -v

Great, what does it all mean?

ls -l —time-style='+%a' - List all files and set the date output to a human readable day name
awk '$6 != "Fri" { print $7 }' - Filter out all files that were created on Friday
grep -v - Some systems show a 'total x' line... if it's there, don't show it
args rm -v - Pass the resulting lines to xargs and execute rm for each of the results