Wednesday, January 8, 2014

How to Delete all files in directory except the ones that start with the letter ?

Delete all files in directory except the ones that start with the letter

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$')

No comments:

Post a Comment