I have a question. How do you delete all hidden and non-hidden files except one in bash? BEcause I am creating a repository, and just now creating a update script.
CodePudding user response:
I would use the extended globbing and dot-globbing features of bash:
shopt -s dotglob extglob
cd /path/to/clean && rm !(file-name-to-keep)
CodePudding user response:
This will delete everything in the current directory that you have permission to remove, recursively, preserving the file named by -path
, and its parent path.
# remove all files bar one
find . -mindepth 1 -not -type d -not -path ./file/to/keep -exec rm -rf {}
# then remove all empty directories
find . -mindepth 1 -type d -exec rmdir -p {} 2>/dev/null
rmdir
will get fed a lot of directories its already removed (causing error messages). rmdir -p
is POSIX. This would not work without -p
.
You can keep more files with additional -path
arguments, and/or glob patterns. The paths must match the starting point, ie. ./
.
CodePudding user response:
This would delete all files (not directories) in the current directory apart from "file-x":
rm `find . -maxdepth 1 -type f | grep -v "^\./file-x\$"`
The find creates a list of all files (including hidden ones). The "grep -v" removes the line "./file-x" from that list.