Recursively find and replace files

2019-03-22 07:14发布

What I want to do is following. I want to create some bat file, that will recursively search for files starting from current directory and replace with the file that I provided. For ex. if I want to search and replace test1.txt, I'm opening this mini app and writing text1.txt, and placing the file that I want to be replaced with.

  • Dir
    • app.bat
    • test1.txt // app will recursively search inside folder 1 and folder 2 and will replace all found results with test1.txt
    • folder 1
    • folder 2

I wonder, if there is ready to go app or bat file for this reason?

1条回答
Summer. ? 凉城
2楼-- · 2019-03-22 07:33

The Batch file below start from current directory, recursively search the file given in the first parameter and copy over it (with same name) the file given in second parameter:

@echo off
set targetName=%~NX1
set replacementFile=%~F2
call :processFolder
goto :EOF

:processFolder
rem For each folder in this level
for /D %%a in (*) do (
   rem Enter into it, process it and go back to original
   cd %%a
   if exist "%targetName%" (
      copy "%replacementFile%" "%targetName%" /Y
   )
   call :processFolder
   cd ..
)
exit /B

For example:

app test1.txt c:\data\replacementfile.txt
查看更多
登录 后发表回答