Glob pattern to match all files that do not start with prefix

Issue

I want to use glob pattern to match all the files in src/ folder that do not start with prefix of two uppercase letters followed by a dot.

The glob should match the following files

foo.txt
foo-bar.txt
foo.bar.baz.txt
fo.txt

But it should not match the following files:

AB.foo.txt
AB.foo-bar.txt
XY.foo.bar.baz.txt
FO.fo.txt

The prefix will always be two uppercase letters (A to Z) followed by a dot.

Solution

glob() can mostly do what you’re looking for, but with some limitations.

You can do this:

glob.glob("src/[!A-Z][!A-Z][!.]*")

which would exclude any files that start with two uppercase letter followed by a dot. However, this particular syntax will also exclude any files with less than 3 characters in the filename. Globbing is similar to shell filename globbing syntax, and in a shell what you’re looking for is more often accomplished with find or grep.

If glob() isn’t flexible enough, you’d have to glob all files and pattern match on your own.

Answered By – sj95126

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published