Bash script to remove all files and directories except specific ones

前端 未结 5 875
无人及你
无人及你 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 17:51

    assuming you have files:

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 a

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 b

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 c

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 d

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 e

    drwxr-xr-x 2 root root 4096 Feb 1 02:17 f

    drwxr-xr-x 2 root root 4096 Feb 1 02:18 nodelete1

    drwxr-xr-x 2 root root 4096 Feb 1 02:18 nodelete2

    You could do:

    ls | grep -v "nodel.\+" | xargs rm -rf

    to use advanced regexp syntax to exclude files.

    Explanation:

    ls --- lists current directory (ls -d to list only directories)

    grep -v --- v flag specifies what NOT TO MATCH + grep allows to write perl style regexp if you supply -P flag

    xargs --- applies action "rm -rf" on each of the items

提交回复
热议问题