在 .bat(批处理文件)中查找并替换导致未知错误的字符串

Find and Replace String causing unknown error in .bat (batch file)

我正在尝试使用批处理替换 .yml 文件中的一些文本。

我的代码:

@echo off
if not defined in_subprocess (cmd /k set in_subprocess=y ^& %0 %*) & exit )
setlocal enableextensions 

set jruby="%~dp0jruby\bin\jruby"
set someDir="%~dp0..\test\test2"

cd %someDir%
copy /y file.yml test_file.yml > NUL
for /f "tokens=2*" %%i in (file.yml) do @set "password=%%i"
echo Your password --- %password% --- will now be encrypted due to security reasons...

%jruby% -S run_file.rb 

for /f "delims=" %%x in (some_file.rb) do set some_key=%%x

FOR /F "tokens=* USEBACKQ" %%F IN (`%jruby% -S encrypt_property_for_yaml encrypt %some_key% %password%`) DO (
SET encrypted_pw=%%F
)
echo Random 32-Bit encryption key created: %some_key%
echo Password was encrypted to: %encrypted_pw%
echo.
echo Encrypted password will be saved in file.yml file...

set "replace=%encrypted_pw%"
set "databaseFile=file.yml"
set "search=%password%"

for /f "delims=" %%i in ('type "%databaseFile%" ^& break ^> "%databaseFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%databaseFile%" echo(!line:%search%=%replace%!
    endlocal
)
pause

此代码块导致错误

set "replace=%encrypted_pw%"
set "databaseFile=file.yml"
set "search=%password%"

for /f "delims=" %%i in ('type "%databaseFile%" ^& break ^> "%databaseFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%databaseFile%" echo(!line:%search%=%replace%!
    endlocal
)
pause

整个过程完美无缺,但是当我到达实际替换发生的最后一个 FOR-BLOCK 时,我总是会收到以下错误:

! was unexpected at this time

一开始我以为是因为回显时缺少右括号,但仍然会导致同样的错误。

*Side note: the method I use to find and replace was originally from here

有趣的是,当我 运行 在一个完全独立的 .bat 文件中使用相同的代码时,它可以完美运行,但是当我将它与包含其他代码的当前批处理文件一起使用时,我总是得到同样的错误。我尝试使用 set 而不是 >>"%databaseFile%" echo(!line:%search%=%replace%!

我尝试使用谷歌搜索,发现了一些与延迟扩展有关的类似情况,但我似乎无法让 FIND and REPLACE 工作。

密码包含结束括号,这被视为代码块的结束。您需要避免出现每个 )

在下面截取的代码中,我添加了替换部分:

set "encrypted_pw=%encrypted_pw:)=^)%"
set "replace=%encrypted_pw%"
set "databaseFile=file.yml"
set "search=%password%"

for /f "delims=" %%i in ('type "%databaseFile%" ^& break ^> "%databaseFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%databaseFile%" echo(!line:%search%=%replace%!
    endlocal
)
pause

或者,更好的是你可以让它更短,让它成为循环中替换本身的一部分:

set "replace=%encrypted_pw%"
set "databaseFile=file.yml"
set "search=%password%"

for /f "delims=" %%i in ('type "%databaseFile%" ^& break ^> "%databaseFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    >>"%databaseFile%" echo(!line:%search%=%replace:)=^)%!
    endlocal
)
pause

编辑:保留空行。

@echo off
set "search=word to search"
set "replace=to replace"
set "databaseFile=file.yml"

for /f "delims=" %%i in ('type "%databaseFile%" ^| find /n /v "^"  ^& break ^> "%databaseFile%" ') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:*]=!"
    >>"%databaseFile%" echo(!line:%search%=%replace%!
    endlocal
)
pause