1

I'm trying to modify the for loop on a list of files from here, adding to it, a check if a sub-string exists in the file name:

for /r %%i in (*) do echo %%i

How can I modify the above windows bat script to check if a sub-string exists in a file name or not?

user3483203
  • 50,081
  • 9
  • 65
  • 94
pyCthon
  • 11,746
  • 20
  • 73
  • 135

2 Answers2

3

I believe you are looking for this:

for /r %i in (*sub_string*) do echo %i

Or if you are using a batch file:

for /r %%i in (*sub_string*) do echo %%i

Here is my directory structure:

enter image description here

Output of running the following command:

for /r %i in (*test*) do echo %i

Is as follows:

C:\Users\czimmerman\Development\CMDTest>for /r %i in (*test*) do echo %i

C:\Users\czimmerman\Development\CMDTest>echo C:\Users\czimmerman\Development\CMD
Test\test1.txt
C:\Users\czimmerman\Development\CMDTest\test1.txt

C:\Users\czimmerman\Development\CMDTest>echo C:\Users\czimmerman\Development\CMD
Test\test2.txt
C:\Users\czimmerman\Development\CMDTest\test2.txt

C:\Users\czimmerman\Development\CMDTest>

Notice there is no notthisone.txt listed.

user3483203
  • 50,081
  • 9
  • 65
  • 94
2

One way is to use string substitution (check [SS64]: Variable Edit/Replace or [SO]: Batch file: Find if substring is in string (not in a file) for more details).
Because it happens in a for loop, Delayed Expansion ([SS64]: EnableDelayedExpansion) must be taken into account.

For example, the following code filters file names that contain "text" and discards the rest (each found file name is printed at the beginning).

script00.bat:

@echo off
setlocal enabledelayedexpansion

for /r %%f in (*) do (
    echo Found: %%f
    set __CURRENT_FILE=%%f
    if not "!__CURRENT_FILE:text=!" == "!__CURRENT_FILE!" (
        echo Filtered: !__CURRENT_FILE!
    )
)

echo Done.

Output:

echo Done.
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q049137405]> dir /b
code00.py
other text.txt
script00.bat
text.txt

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q049137405]> .\script00.bat
Found: e:\Work\Dev\StackOverflow\q049137405\code00.py
Found: e:\Work\Dev\StackOverflow\q049137405\other text.txt
Filtered e:\Work\Dev\StackOverflow\q049137405\other text.txt
Found: e:\Work\Dev\StackOverflow\q049137405\script00.bat
Found: e:\Work\Dev\StackOverflow\q049137405\text.txt
Filtered e:\Work\Dev\StackOverflow\q049137405\text.txt
Done.
CristiFati
  • 38,250
  • 9
  • 50
  • 87