1

I have a textfile (filename.txt) which contains

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

I will be getting a variable passed (ex: product=ABC which will be substring of ProductABC_Test.txt). So I need to fetch the correct test name (ProductABC_Test.txt) from the filename.txt.

I have tried the following code -

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%

But I am not getting the right result.

Dennis van Gils
  • 3,487
  • 2
  • 14
  • 35
  • 1
    You need [Delayed Variable Expansion](http://stackoverflow.com/a/10558905/5047996) because you are setting _and_ reading a variable within a block of code, so `!str!` rather than `%str%`, and also `!str:%product%=!`... – aschipfl Nov 23 '15 at 18:30
  • @aschipfl - your points look great. Now I understand about the Delayed Variable Expansion. Thanks a lot – Jagadish Chandran Nov 23 '15 at 19:23
  • Please note that `DOS` is an Operating System from the 80s/90s! Please use the tag Windows instead. –  Aug 23 '17 at 06:05

1 Answers1

0

You can use the following code to look for the line that contains your substring:

@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
Dennis van Gils
  • 3,487
  • 2
  • 14
  • 35