批处理脚本以修改.properties文件 [英] Batch script to modify .properties file
问题描述
我有一个属性文件(server.properties),它看起来像这样:
I have a properties file (server.properties) and it looks like this:
ipaddress = 10.x.x.x
serverName = someName
ipaddress=10.x.x.x
serverName=someName
以及许多其他值.
假设它位于C:\ Server \ server.properties
有没有一种方法可以使用批处理脚本来修改值.
Let's say it is located at C:\Server\server.properties
Is there a way to modify the values using a batch script.
如果要将serverName从"someName"更改为"myName",该怎么办?我不能使用行号,因为它可以随时更改.
What would I do if I want to change serverName from "someName" to "myName" ? I can't use line numbers because it can change anytime.
这不是我正在尝试找出如何替换属性的值.不要用一个单词替换另一个单词.
I am trying to figure out how to replace the value of a property. Not replacing one word with another.
谢谢.
推荐答案
@ECHO OFF
SETLOCAL
SET "sourcedir=C:\106x"
(
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25967146.txt") DO (
FOR /f "tokens=1*delims==" %%g IN ("%%a") DO (
IF /i "%%g"=="servername" (ECHO(%%g=%~1
) ELSE (ECHO(%%a)
)
)
)>newfile.txt
:: newfile.txt now contains a modified version.
:: This line will overwrite the original
ECHO(MOVE /y newfile.txt "%sourcedir%\q25967146.txt"
GOTO :EOF
您需要更改 sourcedir
的设置以适合您的情况.
You would need to change the setting of sourcedir
to suit your circumstances.
我使用了一个名为 q25967146.txt
的文件,其中包含您的数据以进行测试.更改名称以适合自己.
I used a file named q25967146.txt
containing your data for my testing. Change the name to suit yourself.
产生newfile.txt
Produces newfile.txt
所需的MOVE命令仅被 ECHO
用于测试目的.确认命令正确无误后,将 ECHO(MOVE
)更改为 MOVE
以实际移动文件.nul 禁止显示报告消息(例如 1个文件已移动
)
The required MOVE commands are merely ECHO
ed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE
to MOVE
to actually move the files. Append >nul
to suppress report messages (eg. 1 file moved
)
上面显示的方法故意创建一个新文件,以便可以在不损坏原始版本的情况下查看新版本.
The method shown above deliberately creates a new file in order that the new version can be viewed without damaging the original.
请注意,此版本将在创建新版本时从文件中删除所有空行.如果需要,可以克服这个问题.
Note that this version will remove any empty lines from the file when creating the new version. This can be overcome if required.
要运行此例程,请使用
此批次名称替换文字"
如果替换文本是没有空格或其他分隔符的单个字符串(很可能是这样),则可以省略引号.
If the replacement text is a single string without spaces or other separators (as seems likely) then the quotes can be omitted.
已修正代码-/f ... %% a ... 行的中有一个
delims =="
,这应该是 delims=
(一个 =
.)在中,对于/f ... %% g ...
来说,双 =
是正确的线.
Code fixed - there was a delims=="
in the for /f...%%a...
line, this should be delims=
(one =
.) The double =
is correct in the for /f ... %%g...
line.
要替换文件,请按照指示操作,通过将 ECHO(MOVE
替换为 MOVE
来激活 move
-一旦您确认该过程如您所见,可能已经做了一个小错误和损坏-通过两步操作可以保存.
To replace the file, activate the move
as instructed by replacing ECHO(MOVE
with MOVE
- once you've verified that the procedure is operating correctly. As you've seen, one small error and damage could have been done - saved by the two-step operation.
这篇关于批处理脚本以修改.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!