I need to match results of find with regexp. The files are as:



I need to match all files from all directories ending in xxx.txt where xxx are 3 digits and only those filenames that are not preceded by word pure_. Further, I need to return the full path.

I have all working except excluding the files preceded by pure_:

find /path/ -mindepth 1 -maxdepth 2 -type f | grep -P '.*\.[0-9]{3}.txt' 

I tried:

find /path/ -mindepth 1 -maxdepth 2 -type f | grep -P '.+(?!pure).*\.[0-9]{3}.txt' 

but if I do in say /path/1/:

ls -1 | grep -P '^(?!pure).*\.[0-9]{3}.txt'

that correctly excludes those files, on the other hand:

ls -1 | grep -P '(?!pure).*\.[0-9]{3}.txt'

does not.

So it probably boils down to, how to match within a full path a basename that does not start with pure_. My understanding of regular expressions is insufficient for that, it may have something to do with the atomicity of look arounds which i never understood.


You could just tell find to exclude files that begin with pure_, and also do the grep with the -regex expression:

find ./path -mindepth 1 -maxdepth 2 -type f ! -name 'pure_*' -regex '.*\.[0-9][0-9][0-9].txt$'

With copies in a simulated directory from your example, I get:

| improve this answer | |
  • Depending on your find implementation, you can use [0-9]{3} with either -regextype posix-extended or regextype Extended – Jeff Schaller Mar 12 '18 at 16:10

find without regular expression matching:

find /path -type f ! -name 'pure_*' -name '*[0-9][0-9][0-9].txt'

This will find any regular file in or under the /path directory whose name does not start with pure_ but ends in three digits and .txt.

| improve this answer | |
find -type f | egrep "[0-9]{3}\.txt$" | grep -v pure_

The find looks for files starting in your current directory.

The egrep applies extended regexps, filtering for three digits appended by ".txt" (the dots needs to be escaped as otherwise "Atxt" would match, too), at the end of a line.

The grep filters away (-v) lines with the string "pure_" (I am not sure if the place of the "pure_" is important).

| improve this answer | |
  • This would not report files in a directory called pure_files (for example). – Kusalananda Mar 12 '18 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.