问题
Duplicate
Unable to remove everything else in a folder except FileA
I guess that it is slightly similar to this: delete [^Music]
However, it does not work.
回答1:
Put the following command to your ~/.bashrc
shopt -s extglob
You can now delete everything else in the folder except the Music folder by
rm -r !(Music)
Please, be careful with the command. It is powerful, but dangerous too.
I recommend to test it always with the command
echo rm -r !(Music)
回答2:
The command
rm (ls | grep -v '^Music$')
should work. If some of your "files" are also subdirectories, then you want to recursively delete them, too:
rm -r (ls | grep -v '^Music$')
Warning: rm -r can be dangerous and you could accidentally delete a lot of files. If you would like to confirm what you will be deleting, try looking at the output of
ls | grep -v '^Music$'
Explanation:
- The
lscommand lists directory contents; without an argument, it defaults to the current directory. - The pipe symbol
|redirects output to another command; when the output oflsis redirected in this way, it prints filenames one-per-line, rather than in a column format as you would see if you typelsat an interactive terminal. - The
grepcommand matches lines for patterns; the-vswitch means to print lines that don't match the pattern. - The pattern
^Music$means to match a line starting and ending with Music -- that is, only the string Music; the effect of the^(beginning of line) and$(end of line) characters can also be achieved with the-xswitch, as ingrep -vx Music. - The syntax
command (subcommand)is fish's way of taking the output of one command and passing it over as command-line arguments to another. - The
rmcommand removes files. By default, it does not remove directories, but the-r("recursive") option changes that.
You can learn about these commands and more by typing man command, where command is what you want to learn about.
回答3:
So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.
find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.
来源:https://stackoverflow.com/questions/453581/how-can-i-delete-all-files-in-my-folder-except-music-subfolder