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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.