Sunday, April 17, 2005

Delete all files in directroy except....

In Unix, to delete all the files in a directory except the ones that start with the letter "a", do the following:

rm [!a]*

But let's say there are many files, and you want to delete everything except a file called "my_file". Use grep's inverse matching capability here:

rm $(ls * | grep -v my_file)

Of course if there are other files with "my_file" as part of their filename, then those won't be deleted either. The following will ensure that this doesn't happen:

rm $(ls * | grep -v '^my_file$')

5 comments:

Anonymous said...

Probably naive question, but why are you using $() instead of `` ?

Anonymous said...

In bash, it's more readable and considered better practice to use $() instead of ``. IIRC, sh doesn't have $(), and scripts may need to use `` for compatibility.

Anonymous said...

I have classify turned on by default, and there were several directories, so I did this:

rm -rf $(ls -d --file-type * | grep -v some_file_name)

thanks for the hint.

Doru said...

rm !(my_file)
also works, see man bash, pattern matching

Anonymous said...

Learn the find command.