Reputation: 3
I have a file1.txt with some file names. I want to read from the file and if the file name contains "xyz" string i need to run some commands and if not some other commands Not able to do this and need your help,tried a lot of methods but not able to figure out Here's the sample code i tried:
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2,3 delims=" %%i in (file1.txt) do (
set f=%%i
set z=XYZ
echo !f! >>test.txt
if /i "!f!" == "!z!" (
echo matched >> test.txt
) else (
echo nomatch >> test.txt
)
)
Upvotes: 0
Views: 8148
Reputation: 34909
To compare whether a string contains another one, you can do it like this (note that this is case-insensitive, because the underlying sub-string expansion syntax is case-insensitive on its own):
if "!STRING!"=="!STRING:%SUB%=!" echo Sub-string "%SUB%" NOT found within "!STRING!"
Here the above approach is implemented into your script:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_INFILE=file1.txt"
set "_OUTFILE=test.txt"
set "_SUBSTR=XYZ"
>> "%_OUTFILE%" (
for /F "usebackq tokens=1-3 delims=" %%L in ("%_INFILE%") do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
echo(!LINE!
if not "!LINE!"=="!LINE:%_SUBSTR%=!" (
echo matched
) else (
echo nomatch
)
endlocal
)
)
endlocal
exit /B
In addition, I improved the following things:
>>
by >
to overwrite an already existing file rather than appending to it;_SUBSTR
must not contain such;set
syntax is used throughout the script;Alternatively, you could use the find
command, which returns only those lines within file1.txt
that contain the sub-string in %SUB%
; add the /I
option to do a case-insensitive search:
find "%SUB%" "file1.txt"
Upvotes: 4