问题
I need a batch file witch will:
check inside user.cfg file for string "g_language = Russian" and leave it if finds it but if sting is set to "g_language = English" then set it to "g_language = Russian"
wait for some.exe to start and when it is started
change string "g_language = Russian" to "g_language = English"
How can I do this?
I used this code but my result is:
Russian=g_language = English= Russian
@echo off &setlocal
set "search=g_language = Russian"
set "replace=g_language = English"
set "textfile=user.cfg"
set "newfile=user.bak"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
del %textfile%
rename %newfile% %textfile%`
回答1:
@echo off &setlocal
set "Russian=g_language = Russian"
set "English=g_language = English"
set "textfile=user.cfg"
set "newfile=user.bak"
Call :SwapLang Russian
Start "" some.exe
Timeout /t 5
Call :SwapLang English
Goto :Eof
:SwapLang %1 byRef
( for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
setlocal EnableDelayedExpansion
If /I "!line:~0,12!" Equ "g_language =" (
echo(!%1!
) Else (
echo(!line!
)
endlocal
)) > "%newfile%"
del %textfile%
rename %newfile% %textfile%
Goto :Eof
回答2:
Heres an alternative to the great answer already given.
I haven't been able to test this, (please try it in a test environment first), and only do so if you feel you would benefit from the slightly different approach.
@Echo Off
Set "fexe=some.exe"
Set "fcfg=user.cfg"
Set "fbak=user.bak"
Set "sstr=g_language"
Set "rlng=Russian"
Set "elng=English"
If Exist "%fbak%" (If Not Exist "%fcfg%" (Copy "%fbak%" "%fcfg%"
) Else Copy "%fcfg%" "%fbak%") Else If Exist "%fcfg%" (Copy "%fcfg%" "%fbak%"
) Else Exit/B
QProcess "%fexe%">Nul 2>&1 &&(FindStr/IC:"%sstr% = %elng%" "%fbak%">Nul||(
Call :Sub "%rlng%" "%elng%"))||(
FindStr/IC:"%sstr% = %rlng%" "%fbak%">Nul||(Call :Sub "%elng%" "%rlng%"
Start "" "%fexe%"))
Exit/B
:Sub
(For /F Delims^= %%A In ('FindStr $ "%fbak%"') Do If /I "%%A"=="%sstr% = %~1" (
Echo %sstr% = %~2) Else Echo %%A)>"%fcfg%"
I have made it so that you should only need to check/adjust the items on lines 3 to 8.
The general idea:
- If neither
user.cfganduser.bakexist, exit. - If only one of
user.cfgoruser.bakexists copy one to the other. - If both
user.cfganduser.bakexist, copyuser.cfgtouser.bak. - If
some.exeis running anduser.cfg'sg_languageis notEnglishchange it toEnglish. - If
some.exeis not running anduser.cfg'sg_languageis notRussianchange it toRussianand runsome.exe.
Of course none of this matters if user.cfg changes do not take effect until some.exe is restarted.
来源:https://stackoverflow.com/questions/45879928/batch-check-and-replace-string-then-wait-for-a-process