How to delete all files from a folder except one or two in a Linux terminal?
I have 100 image files in a directory and one
I want to delete all files except that
From within the directory, list the files, filter out all not containing 'file-to-keep', and remove all files left on the list.
ls | grep -v 'file-to-keep' | xargs rm
To avoid issues with spaces in filenames (remember to never use spaces in filenames), use
find 'path' -maxdepth 1 -not -name 'file-to-keep' -print0 | xargs -0 rm
Or mixing both, use
-z to manage the
-print0 names from