3 Ways to Delete All File in a Directory Except One or Few Files with extensions

发布时间 2023-07-28 09:32:08作者: jetwill
# https://www.tecmint.com/delete-all-files-in-directory-except-one-few-file-extensions/
# https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html

shopt -s extglob
# s means set

# To delete all files in a directory except filename, type the command blow:
rm -v !("filename")

# To delete all files with the exception of filename1 and filename2:
rm -v !("filename1"|"filename2") 

# The example below shows how to remove all files other than all .zip files interactively:
rm -i !(*.zip)

# you can delete all files in a directory apart from all .zip and .odt files as follows, while displaying what is being done:
rm -v !(*.zip|*.odt)

# Once you have all the required commands, turn off the extglob shell option like so:
shopt -u extglob
# -u means unset