Recursively find and replace files

时光怂恿深爱的人放手 提交于 2019-12-04 14:39:55

问题


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:


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


来源:https://stackoverflow.com/questions/10422433/recursively-find-and-replace-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!