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

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.

Upvotes: 0

Views: 3026

Answers (3)

msantoro12
msantoro12

Reputation: 126

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.

Upvotes: 0

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)

Upvotes: 4

A. Rex
A. Rex

Reputation: 31981

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.

Upvotes: 2

Related Questions