Remove all files except some from a directory

前端 未结 19 1161
生来不讨喜
生来不讨喜 2020-11-30 16:36

When using sudo rm -r, how can I delete all files, with the exception of the following:

textfile.txt
backup.tar.gz
script.php
database.sql
info.         


        
19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 17:02

    Since no one yet mentioned this, in one particular case:

    OLD_FILES=`echo *`
    ... create new files ...
    rm -r $OLD_FILES
    

    (or just rm $OLD_FILES)

    or

    OLD_FILES=`ls *`
    ... create new files ...
    rm -r $OLD_FILES
    

    You may need to use shopt -s nullglob if some files may be either there or not there:

    SET_OLD_NULLGLOB=`shopt -p nullglob`
    shopt -s nullglob
    FILES=`echo *.sh *.bash`
    $SET_OLD_NULLGLOB
    

    without nullglob, echo *.sh *.bash may give you "a.sh b.sh *.bash".

    (Having said all that, I myself prefer this answer, even though it does not work in OSX)

提交回复
热议问题