I need to create a purge script to remove any foreign directories from a specific list of directories.

My idee was to do something like this :

 #!/bin/ksh find /data/${USER}/SAS/ -type d ! -name 'SE' | find /data/${USER}/SAS/ -type d ! -name 'Rejet' | find /data/${USER}/SAS/ -type d ! -name 'Acq' | find /data/${USER}/SAS/ -type d ! -name 'Archiv' | find /data/${USER}/SAS/ -type d ! -name 'Cloture' | find /data/${USER}/SAS/ -type d ! -name 'Emis' | find /data/${USER}/SAS/ -type d ! -name 'Ident' | find /data/${USER}/SAS/ -type d ! -name 'Irr*' | find /data/${USER}/SAS/ -type d ! -name 'Recep*'

and then -type f -exec rm {} \; but don't really know how to do this.


To remove all folders within path /data/${USER}/SAS/ except those are in predefined/specified list - use the following optimized find approach:

find /data/${USER}/SAS/ -type d -regextype posix-egrep \
    ! -regex ".*/(SE|Rejet|Acq|Archiv|Cloture|Emis|Ident|Irr.*|Recep.*)" \
    ! -name "SAS" -exec rm -rf {} \;

Since you're using ksh, it should just be a matter of:

(FIGNORE='@(.|..)'; cd /data/"$USER"/SAS/ && 
   echo rm -rf -- !(SE|Rejet|Acq|Archiv|Cloture|Emis|Ident|Irr*|Recep*)/)

(remove echo when happy)

Which would remove all the directories except those that match that list (leaving the non-directory files alone).

Remove the FIGNORE part if you don't want to remove hidden directories.

Note that it will also consider symlinks to directories (and depending on the rm implementation either delete the symlink or the content of the target).

With find, you'd do:

cd /data/"$USER"/SAS &&
  find . ! -name . -prune \
    ! -name SE \
    ! -name Reject \
    ! -name Acq \
    ! -name Archiv \
    ! -name Cloture \
    ! -name Emis \
    ! -name Ident \
    ! -name 'Irr*' \
    ! -name 'Recep*' -type d -exec echo rm -rf {} +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.