Michael
Michael

Reputation: 22947

regular expression to exclude filetypes from find

When using find command in linux, one can add a -regex flag that uses emacs regualr expressions to match.

I want find to look for all files except .jar files and .ear files. what would be the regular expression in this case?

Thanks

Upvotes: 32

Views: 27963

Answers (4)

user2268788
user2268788

Reputation: 266

find . -regextype posix-extended -not -regex ".*\\.(jar|ear)"

This will do the job, and I personally find it a bit clearer than some of the other solutions. Unfortunately the -regextype is required (cluttering up an otherwise simple command) to make the capturing group work.

Upvotes: 10

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

EDIT: New approach:

Since POSIX regexes don't support lookaround, you need to negate the match result:

find . -not -regex ".*\.[je]ar"

The previously posted answer uses lookbehind and thus won't work here, but here it is for completeness' sake:

.*(?<!\.[je]ar)$

Upvotes: 15

Naftis
Naftis

Reputation: 4559

Using a regular expression in this case sounds like an overkill (you could just check if the name ends with something). I'm not sure about emacs syntax, but something like this should be generic enough to work:

\.(?!((jar$)|(ear$)))

i.e. find a dot (.) not followed by ending ($) "jar" or (|) "ear".

Upvotes: 0

dogbane
dogbane

Reputation: 274592

You don't need a regex here. You can use find with the -name and -not options:

find . -not -name "*.jar" -not -name "*.ear"

A more concise (but less readable) version of the above is:

find . ! \( -name "*.jar" -o -name "*.ear" \)

Upvotes: 49

Related Questions