Reputation: 1455
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
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
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 patternUpvotes: 1