I try to find a string "blabla" inside a file. If I find the string I replace it with "bloblo", if not do nothing. And I want to do this operation for all the files that I have in a folder.

When I apply the script on one file, it works well. When I use a for loop it doesn't work. it does not enter inside the for loop

Here is my script:

    set "Var1=blabla"
    set "Var2=bloblo"

FOR %%i IN (C:\Users\UserName\Desktop\TEST\*.txt) DO (      
        find /c "%Var1%" %%i
        if %errorlevel% equ 1 goto notfound
        call PathFile\FUNCTION_REPLACE.cmd %Var1% %Var2% %%i

        :notfound
)

I use a script "Function_replace" to replace the values, here is the script:

SetLocal EnableExtensions DisableDelayedExpansion

Set "search=%~1"
Set "replace=%2"
Set "File=%3"

For /F "Tokens=1*Delims=]" %%A In ('Find /V /N ""^<"%File%"^&Break^>"%File%"'
)Do (Set "line=%%B"
    SetLocal EnableDelayedExpansion
    (If Not "%%B"=="" (Echo(!line:%search%=%replace%!)Else Echo()>>"%File%"
    EndLocal)

I used to use directly the call of my replace function for each files of my folder. But it takes a long time to go inside each file. That's why I want to check before going inside each file, if the string exists or not (by using find /c).

Can you spot where is the issue coming from?

2 Answers

1
Compo On Best Solutions

Based upon your latest edit, here's an example which sends only the files containing the string to be replaced, to the sub-function:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "search=%~1"
Set "replace=%~2"
For /F Delims^=^ EOL^= %%A In ('FindStr /LIMP "%search%" *.*')Do Call :Sub "%%A"
GoTo :EOF

:Sub
Set "File=%~1"
For /F "Tokens=1*Delims=]" %%A In ('Find /V /N ""^<"%File%"^&Break^>"%File%"'
)Do (Set "line=%%B"
    SetLocal EnableDelayedExpansion
    (If Not "%%B"=="" (Echo(!line:%search%=%replace%!)Else Echo()>>"%File%"
    EndLocal)

Please note that the FindStr command uses only example options, whilst the /M option is important to this solution you should check the output from FindStr /? to determine which of the others you would consider the most appropriate.

0
Gerhard Barnard On

Why not simply list all files that has the string and exclude the files that don't? That seems like a more obvious plan to me:

@echo off
set "search=blabla"
for /f "delims=" %%i in ('findstr /m %search% "%USERPROFILE%\Desktop\TEST\*.txt"') do (
  echo found "%search%" in "%%~fi"
)

If you want to still show files that does not contain the path, then @stephan already posted a comment on how to, no need for me to repeat.