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
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