4

I don't understand why findstr doesn't work as I want.

I have the following files in my test directory:

aaa.jpg
bbb.png
ccc.svg

aaa_s.jpg
bbb_s.png
ccc_s.svg

aaa_small.jpg
bbb_small.png
ccc_small.svg

And I have the following line to pass directly to cmd.exe:

for /f "delims=" %f in ('dir /b /a:-d ^| findstr /ile "gif jpg png svg" ^| findstr /ie "_s.*"') do echo "%f"

To my opinion, it should match the following files:

aaa_s.jpg
bbb_s.png
ccc_s.svg

However, it's actually matches

aaa_s.jpg
bbb_s.png
ccc_s.svg

aaa_small.jpg
bbb_small.png
ccc_small.svg

Yes, I understand that the problem is that the dot works as "any character" instead of being treated literally.

findstr /ie "_s.*"

Bot how can I escape it? Using backslash, i.e. changing it to

findstr /ie "_s\.*"

doesn't work.

2
  • The . is in fact escaped with \ , according to this post serverfault.com/questions/123483/…. Is there something else wrong with your script? Btw nobody understands how findstr works :) It seems that David already answered, so there you go Apr 15, 2020 at 18:28
  • "Btw nobody understands how findstr works" - Haha. :)
    – john c. j.
    Apr 15, 2020 at 18:37

2 Answers 2

5

How can I escape the wildcard . in order to match a literal . character?

You are on the right lines with using a \, however you need an additional . in order to find the remaining characters.

findstr /ie "_s\..*"

Example (type and a cmd shell):

F:\test>dir /b /a:-d | findstr /ile "gif jpg png svg" | findstr /ie "_s.*"
aaa_s.jpg
bbb_s.jpg
ccc_s.jpg
aaa_small.jpg
bbb_small.jpg
ccc_small.jpg

F:\test>dir /b /a:-d | findstr /ile "gif jpg png svg" | findstr /ie "_s\..*"
aaa_s.jpg
bbb_s.jpg
ccc_s.jpg

So your batch file should contain:

for /f "delims=" %f in ('dir /b /a:-d ^| findstr /ile "gif jpg png svg" ^| findstr /ie "_s\..*"') do echo "%f"
1
  • Agreed. The REGEXP .* says 1 or more characters. The REGEXP \..* says a dot, plus one or more characters.
    – Scottie H
    Apr 15, 2020 at 18:32
3

For this specific task you can also escape the "." in the findstr by not using it if you replace:

dir /b /a:-dwhere .:*_s.*

findstr /ie "_s\.*"findstr /ei "gif jpg png svg"

where .:*_s.*|findstr /ei  "gif  jpg  png  svg"

for /f delims^= %f in ('where .:*_s.*^|findstr /ei  "gif  jpg  png  svg"')do echo "%~nxf"

You must log in to answer this question.

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