首页 > 解决方案 > 使用批处理脚本更新属性

问题描述

我正在编写一个批处理脚本来更新属性文件。我能够更新属性文件并将输出重定向到另一个文件。但我想更新相同的属性文件并保持所有注释和空行不变。

示例:项目属性

Set "portNum=8080"
Set "hostname=localhost"

Set "FindportNum=^<port_number^>"
Set "Findhost=^<host^>"


Set "username=someusername"
Set "password=somepassword"
Set "applicationAdminstratorUsername=someapplicationAdminstratorUsername"
Set "applicationAdminstratorPassword=someapplicationAdminstratorPassword"


Set "textFile=C:\Users\Varun\...\installer\none.properties"
Set "textFileOut=C:\Users\...\installer\NewData.txt"
@Echo off&SetLocal
( for /f "usebackq tokens=1* delims==" %%i in (
"%textFile%"
) do If "%%i" equ "Username" (
echo Username=%username%
) else If "%%i" equ "Password" (
echo Password=%password%
) else If "%%i" equ "consumer_key" (
echo consumer_key=%consumerKey%
) else If "%%i" equ "consumer_secret" (
echo consumer_secret=%consumerSecret%
) else If "%%i" equ "c360rest.username" (
echo c360rest.username=%applicationAdminstratorUsername%
) else If "%%i" equ "c360rest.password" (
echo c360rest.password=%applicationAdminstratorPassword%
) else if "%%j" neq "" (
      echo %%i=%%j
   ) else (
      echo %%i
   )
) >C:\Users\...\installer\NewData.txt
pause

请告诉我如何直接更新属性文件而不将其处理后的输出重定向到另一个文件。

谢谢

标签: batch-file

解决方案


您不能立即执行此操作(使用简单的方法)。该文件无法访问,因为它将被另一个进程使用。您可以做的是创建一个临时文件,然后type将其复制到原始none.properties文件。

)>C:\Users\...\installer\NewData.txt
rem OPTIONAL; added for safety: timeout to be sure the file is closed:
timeout 2 >nul
(type "C:\Users\...\installer\NewData.txt")>"C:\Users\Varun\...\installer\none.properties"
del "C:\Users\...\installer\NewData.txt"
pause

推荐阅读