I am trying to write a very simple Bash shell script that will cd in a specific directory, it will remove all files and directories except some few selected ones and then cd
If you have a recent version of find
, then use:
find . -not -regex "filename1|filename2|filename3" -print
Check the output and replace -print
with -delete
if it prints only the files that you really want to delete.
If your version of find
doesn't support -delete
, use -type f -exec rm "{}" \;
Note that this will only delete files. This is important: If you say to keep file x
but that file is in a folder y
, then it would ignore x
only to delete it later with the whole folder y
.
To get rid of all empty folders (and this preserving the files you want to keep):
find . -type d -empty -exec rmdir "{}" \;
(source: How to Find and Delete Empty Directories and Files in Unix)