在 windows 批处理文件中查找包含子字符串的字符串

Find a string containing a substring in windows batch file

我有一个文本文件 (filename.txt),其中包含

ProductABC_Test.txt
ProductDEF_Test.txt
ProductHIG_Test.txt
ProductIJK_Test.txt

我将传递一个变量(例如:product=ABC,它将是 ProductABC_Test.txt 的子字符串)。所以我需要从 filename.txt.

中获取正确的测试名称 (ProductABC_Test.txt)

我试过下面的代码-

SETLOCAL ENABLEEXTENSIONS
@echo off
set product=ABC
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (filename.txt) do 
(
    set str=%%A
    if NOT %str% == !%str:product=% 
    (
        set test_suite=%%A
    )
)
ENDLOCAL
echo %test_suite%

但是我没有得到正确的结果。

您可以使用以下代码查找包含您的子字符串的行:

@echo off
SETLOCAL ENABLEEXTENSIONS
set product=ABC
set test_suite="not found"
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (filename.txt) do (
    set str=%%A
    Echo.!str! | findstr /C:"!product!">nul
    if !errorlevel!==0 set test_suite=!str!
)
echo %test_suite%
pause