I'm trying to replace some text in a .yml
file using batch.
My code:
@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
The error occurs due to this code block
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
The whole thing works perfectly, but as soon as I reach the last FOR-BLOCK
where the actual replace takes place, I always get the following error:
! was unexpected at this time
At first I thought it was due to the missing closing bracket on echo, but that still causes the same error.
*Side note: the method I use to find and replace was originally from here
The funny thing is, when I run the same code in a completely separate .bat file, it works flawlessly, but when I use it with the current batch file including other code, I always get the same error. I tried using set
instead of >>"%databaseFile%" echo(!line:%search%=%replace%!
I tried googling, found some similar situations where it has something to do with the delayedexpansion but I can't seem to get the FIND and REPLACE
to work.