ivanceras
ivanceras

Reputation: 1455

How do I delete certain files in the current directory that doesn't match the given pattern?

using rm *.sh to delete files ending in .sh is easy and understandable. But how do i delete all files in the current directory that does not end in .jar something like rm * -except *.jar

Upvotes: 2

Views: 6026

Answers (3)

thkala
thkala

Reputation: 86333

Try this:

find . -mindepth 1 -maxdepth 1 ! -name '*.jar' | sort

If you really want to delete all the files in its output, then just do

find . -mindepth 1 -maxdepth 1 ! -name '*.jar' -delete

You can read the find(1) manual page for more information on this really powerful tool.

EDIT:

Since the -delete flag is only found in GNU find > 4.2.3 (as pointed out by SiegeX), here are a couple of alternatives, which also make sure we are not trying to delete directories:

find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -print0 | xargs -0 -r rm -f

The -r xargs flags is a GNU extension, so this is slightly more portable (it works on *BSD), but not as clean:

find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -print0 | xargs -0 rm -f

As a last - but most portable - resort:

find . -mindepth 1 -maxdepth 1 ! -type d ! -name '*.jar' -exec rm '{}' ';'

This has the disadvantage of invoking rm separately for each file, which makes it significantly slower.

Upvotes: 6

SiegeX
SiegeX

Reputation: 140257

You can do this by enabling the extended glob extglob option and then putting your pattern inside !() like so:

shopt -s extglob;
rm !(*.jar)

Note that extglob also gives you the following:

  • ?() -- Match zero or one of the pattern
  • *() -- Match zero or more of the pattern
  • @() -- Match exactly one of the pattern
  • !() -- Match anything except the pattern

Upvotes: 1

ssegvic
ssegvic

Reputation: 3142

echo $(ls | grep -v '.jar$')

rm $(ls | grep -v '.jar$')

Upvotes: 1

Related Questions