- 1 year ago
In windows how to iterate over given directory and do replace operation in file using batch command?
To iterate over a given directory and perform a replace operation in files using a batch command on Windows, you can use a combination of the FOR
loop and the FINDSTR
command. Here's an example of how you can achieve it:
batch@echo off
setlocal
set "directory=C:\path\to\directory"
set "searchText=oldText"
set "replaceText=newText"
for /R "%directory%" %%F in (*) do (
if "%%~xF" NEQ ".bat" (
echo Processing "%%~nxF"
(
for /F "usebackq tokens=*" %%A in ("%%F") do (
echo %%A | findstr /R /C:"%searchText%" >nul
if not errorlevel 1 (
set "line=%%A"
setlocal enabledelayedexpansion
set "line=!line:%searchText%=%replaceText%!"
echo(!line!
endlocal
) else (
echo %%A
)
)
) > "%%F.tmp"
move /y "%%F.tmp" "%%F" >nul
)
)
endlocal
Make sure to replace "C:\path\to\directory"
with the actual path to the directory you want to iterate over. Set the "oldText"
and "newText"
variables with the text you want to search and replace, respectively.
In this example, the script will iterate over all files in the specified directory and its subdirectories. It skips processing .bat
files to prevent modifying the batch script itself. For each file, it reads the contents line by line and performs the replace operation using the FINDSTR
command. The modified lines are then redirected to a temporary file. Finally, the temporary file is renamed to replace the original file.
Please note that this script performs a simple text replacement on each line of the files. If you need more complex replacements or want to modify other types of files, you may need to use different tools or techniques.