Bash script to remove all files and directories except specific ones

前端 未结 5 897
无人及你
无人及你 2021-01-04 17:12

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

5条回答
  •  轮回少年
    2021-01-04 18:00

    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)

提交回复
热议问题