tags:

views:

671

answers:

2

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.

+2  A: 

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.

A. Rex
+3  A: 

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)
Masi
he asked about fish shell, this is a bash option. does it also work in config.fish?
bjeanes
@bjeanes: Fish shell is buggy, so I changed the question. I considered Bash in answering the question.
Masi