Windows bat脚本for循环,如果字符串中的子字符串

问题描述 投票:0回答:2

我正在尝试修改文件列表from here上的for循环,添加它,检查文件名中是否存在子字符串:

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

如何修改上面的windows bat脚本以检查文件名中是否存在子字符串?

windows batch-file cmd
2个回答
2
投票

我相信你在寻找这个:

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

或者,如果您使用的是批处理文件:

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

这是我的目录结构:

enter image description here

输出运行以下命令:

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

如下:

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>

请注意,没有列出notthisone.txt


1
投票

一种方法是使用字符串替换(有关详细信息,请查看[SS64]: Variable Edit/Replace[SO]: Batch file: Find if substring is in string (not in a file))。 因为它发生在for循环中,所以必须考虑延迟扩展([SS64]: EnableDelayedExpansion)。

例如,以下代码过滤包含“text”的文件名,并丢弃其余文件名(每个找到的文件名在开头打印)。

code.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!
    )
)

输出:

e:\Work\Dev\StackOverflow\q049137405>code.bat
Found: e:\Work\Dev\StackOverflow\q049137405\code.bat
Found: e:\Work\Dev\StackOverflow\q049137405\other code.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\text.txt
Filtered: e:\Work\Dev\StackOverflow\q049137405\text.txt
© www.soinside.com 2019 - 2024. All rights reserved.