使用DOS批处理脚本:在属性文件中找到一行并替换文本 [英] Using DOS batch script: find a line in a properties file and replace text
问题描述
尝试使用批处理文件替换特定行中属性文件中的字符串.我知道,无需使用临时文件即可完成此操作,正如我之前所见,但是却忘记了如何做.
Trying to replace a string in a properties file on a certain line by using a batch file. I know that this can be done WITHOUT the use of a temp file, as I have seen it before, but forgotten how to do it.
我知道,如果我有一个包含以下内容的var.properties文件:
I know that if I have a var.properties file that contains this:
CLASSPATH=bsh.jar;other.jar
VARTEST=dummy
ANOTHERVAR=default
我试图在不更改属性文件顺序的情况下更新.properties文件中的CLASSPATH值.
I am trying to update the CLASSPATH value in the .properties file without changing the order of the properties file.
这是一个属性文件,因此我相信答案将与使用有关:
This is a properties file and so I believe the answer would be related to using:
for /f "tokens=1,2* delims==" %%i in (var.properties) do (
@echo Key=%%i Val=%%j
)
推荐答案
我终于崩溃了,接受了一个使用临时"文件的方法.将延迟扩展与'!'一起使用角色解决了我的问题.这种成功的大部分归功于 mecaflash 的输入.
I finally broke down and accepted a method using a "temp" file. Using delayed expansion with the '!' character solved my question. Much of this success was due to input by mecaflash .
您可以使用以下命令调用此脚本: CALL Script.bat PropKey NewPropValue文件名
You can call this script with: CALL Script.bat PropKey NewPropValue Filename
@echo off
:: script for updating property files
SETLOCAL EnableExtensions
SETLOCAL EnableDelayedExpansion
if "%3"=="" (
ECHO Script will optionally accept 3 args: PropKey PropVal File
SET PROPKEY=UseCompression
SET PROPVAL=false
SET FILE=config.properties
) ELSE (
SET PROPKEY=%1
SET PROPVAL=%2
SET FILE=%3
)
FINDSTR /B %PROPKEY% %FILE% >nul
IF %ERRORLEVEL% EQU 1 GOTO nowork
MOVE /Y "%FILE%" "%FILE%.bak"
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%FILE%.bak" ^|FIND /N /I "%PROPKEY%"`) DO (
SET LINE=%%A
)
FOR /F "tokens=1,2* delims=]" %%S in ("%LINE%") DO SET LINE=%%S
SET /A LINE=%LINE:~1,6%
SET /A COUNT=1
FOR /F "USEBACKQ tokens=*" %%A IN (`FIND /V "" ^<"%FILE%.bak"`) DO (
IF "!COUNT!" NEQ "%LINE%" (
ECHO %%A>>"%FILE%"
) ELSE (
ECHO %PROPKEY%=%PROPVAL%>>"%FILE%"
ECHO Updated %FILE% with value %PROPKEY%=%PROPVAL%
)
SET /A COUNT+=1
)
GOTO end
:nowork
echo Didn't find matching string %PROPKEY% in %FILE%. No work to do.
pause
:end
这篇关于使用DOS批处理脚本:在属性文件中找到一行并替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!