4

For instance, I want to remove all the files in a directory except for the .tar file from whence they came. I could do something like:

find . -maxdepth 0 | grep -v '.tar$' | xargs rm -f

but is there a way to do is just using rm and shell pattern matching? Feel free to specify it using bash or other commonly available shells, or with extended options, if it can't be done with vanilla sh.

I found a similar question about avoiding directories and subdirectories with find, but not with shell patterns.

4 Answers4

9

You can do it with extended globbing.

shopt -s extglob

then

rm !(file.tar)

This works in bash 3.2.39 at a minimum

Cian
  • 5,878
0

Try this perhaps

find . -maxdepth 0 \! -name '*.tar' -exec echo rm -f {} \;

Remove the echo preceding the rm if it looks right.

Yes, but is there a shell pattern?

I don't think so. At least not in the versions of bash I am familiar with. From the other answers it appears that newer versions may be more functional.

Zoredache
  • 133,737
0

I don't think what you want to achieve is possible.

You could however simplify the command you have:

find . -maxdepth 0 -not -name '*.tar' -exec rm -f {} +
Dan Carley
  • 26,127
0

Edit:

Read the question to fast... But in to continue with my post anyways... :-) If you want to delete all files but tar files recursively with zsh:

rm -rf **/^*.tar(.)

Non-Recursive:

rm -rf ^*.tar(.)

The new bash 4.0 and and zsh support recursive globbing. To enable it in bash use:

shopt -s globstar

It works like:

 rm -rf **/*.tar.gz
Kyle Brandt
  • 85,693