22

I thought this would do the trick:

find src -type f -regextype egrep -regex '.*(?<!\.d)\.ts'

But it doesn't seem to be matching anything.

I think that should work, but I guess this "egrep" flavor doesn't support negative backreferences unless I didn't escape something properly.

For reference,

 % find src -type f
src/code-frame.d.ts # <-- I want to filter this out
src/foo.ts
src/index.ts

Is there another quick way to filter out .d.ts files from my search results?

 % find --version
find (GNU findutils) 4.7.0-git
1

3 Answers 3

71

I don't believe egrep supports that syntax (your expression is a Perl compatible regular expression). But you don't need to use regular expressions in your example, just have multiple -name tests and apply a ! negation as appropriate:

find src -type f -name '*.ts' ! -name '*.d.ts'
2
  • Is the space needed? i.e. will !-name '*.d.ts' work?
    – hongsy
    Jan 16, 2020 at 14:40
  • Yes, it is required. Try it and see for yourself.
    – bxm
    Jan 17, 2020 at 8:17
29

You can get the result you want by filtering on file names only, negating the test for files you don’t want:

find src -type f -name \*.ts ! -name \*.d.ts
2
  • What's the difference between \*.ts and '*.ts'?
    – hongsy
    Jan 16, 2020 at 14:41
  • They’re different ways of preventing expansion: \*.ts escapes the *, so it’s not considered as a globbing character, and '*.ts' single-quotes the whole expression, so none of it is expanded. Jan 16, 2020 at 14:43
6

A simple (maybe less efficient) approach can be filter out the don't-want string.

find -name "*.ts" | egrep -v "\.d\.ts$"
4
  • 5
    This would fail to filter out files that happen to have names ending in .d.ts but that also has a newline preceding that part of the filename. It's an unlikely technicality, but Unix filenames may contain newlines.
    – Kusalananda
    Dec 18, 2019 at 20:37
  • yes you are right, however from the data posted seems that is not the case and can be a valid solution candidate Dec 18, 2019 at 20:41
  • 4
    Also, such special cases (if needed, or there is security concern) could be handled with for example find -name "*.ts" -print0 | egrep -vzZ "\.d\.ts$" | xargs -0i printf '{}\n'. I like this answer as additional one as it gives option for more complex handlings if needed (grep -P, perl -0, etc) Dec 19, 2019 at 0:31
  • So can Windows apparently. Took me a long time to figure out why I couldn’t delete the “Icon” files that kept appearing in imported files.
    – WGroleau
    Dec 19, 2019 at 5:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .