How can I delete all files in my folder, except Music -subfolder?

寵の児 提交于 2019-12-13 03:48:43

问题


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 ls command lists directory contents; without an argument, it defaults to the current directory.
  • The pipe symbol | redirects output to another command; when the output of ls is redirected in this way, it prints filenames one-per-line, rather than in a column format as you would see if you type ls at an interactive terminal.
  • The grep command matches lines for patterns; the -v switch 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 -x switch, as in grep -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 rm command 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!