Thursday, July 25, 2019

Replace the string for file(s) by batch file

1 Replace the string for all files in a directory.
@ECHO OFF
set "prefix=_backup"
set "old=%~1" 
set "new=%~2"
set "dir=%~3"

Setlocal enableDelayedExpansion
for /r %dir% %%a in (*.*) do ( rem echo %%a
    set "file=%%a"
    set "outFile=%%a %prefix%"
    (for /f "usebackq delims=" %%b in ("!file!") do ( rem echo %%b
        set "line=%%b"
        set "line=!line:%old%=%new%!"
        echo !line!
        rem echo %%~da%%~pa%%~na%prefix%%%~xa

    )) > "%%~da%%~pa%%~na%prefix%%%~xa"
    del /Q "%%a"
    move /y "%%~da%%~pa%%~na%prefix%%%~xa" "%%a"
)

Run:
r.bat 2CurrCnvtSp.sp 2CurrCnvt2Sp.sp C:\vss_root

2 Replace the string for specific file.
@ECHO OFF
set "prefix=_backup"
set "old=%~1" 
set "new=%~2"
set "file=%~3"

Setlocal enableDelayedExpansion
(for /f "tokens=1* delims=:" %%a in ('findstr /n ".*" "%file%"') do (
    set "line=%%b"
    if "!line!" neq "" ( 
    set "line=!line:%old%=%new%!" 
    ) 
echo=!line!
)) > "%file%%prefix%"
endlocal
del /Q "%file%"
move /y "%file%%prefix%" "%file%"

Run:
C:\>r.bat 2CurrCnvtSp.sp 2CurrCnvt2Sp.sp "C:\vss_root\ApplicationDB\Stored Proce
dures\2CurrCnvt2Sp.sp"

No comments:

Post a Comment