首页 > 解决方案 > 通过跳过和打印注释和空行从批处理文件更新属性文件

问题描述

我正在使用批处理文件更新属性文件。我想知道是否可以通过跳过和打印注释行和空白行来更新属性文件。我在属性文件中有一些默认情况下没有任何值的键。如果我保留=为分隔符,那么在执行 echo%%A=%%B时,对于注释行,我=会在行尾获得额外的内容。

下面是我的批处理文件:

echo off
 Set "Parametervalue=dev"
 Set "baseURLvalue=https://prodweb-dev.net/start"
 Set "urlvalue=/client/versions-6.0.1.xml"
 (for /f "usebackq tokens=1* delims==" %%A IN (
 myfile.properties
 ) do if "%%A" equ "Parameter" ( 
 echo Parameter=%Parametervalue%
 ) else if "%%A" equ "baseURL" (
 echo baseURL=%baseURLvalue%
 ) else if "%%A" equ "url" (
 echo url=%urlvalue%
 ) else (echo %%A=%%B)
 )>temp.properties

预期带有注释行和空白行的更新属性作为原始文件如下:

#configuration

#baseURL(mandatory)
baseURL=https://prodweb-dev.net/start

#descriptorurl(mandatory) 
#url=/client/versions-6.0.1.xml
url=/client/versions-6.0.1.xml

#Title (optional, new property, default value is "??") 
Title=

#ClientParameter  (optional, no default value) - parameters which will  be     passed to startup file and are accessible by the client application as     environment variable
Parameter=dev

#BackgroundImage (optional, default Image with Daimler logo) 
BackgroundImage=

下面是得到的输出:

#configuration=
#baseURL(mandatory)=
baseURL=https://prodweb-dev.net/start
#descriptorurl(mandatory) =
#url=/client/versions-6.0.1.xml
url=/client/versions-6.0.1.xml
#Title (optional, new property, default value is "??") =
Title=
#ClientParameter  (optional, no default value) - parameters which will be     passed to startup file and are accessible by the client application as     environment variable=
Parameter=dev
#BackgroundImage (optional, default Image with Daimler logo) =
BackgroundImage=

标签: batch-filecmd

解决方案


这将根据需要替换所有文本,而其他行保持不变。我将在我的电脑上进行一次更改,因为位置搜索是一种临时措施,因为我无法通过手机进行测试。

@echo off
setlocal enabledelayedexpansion

set "iofile=myfile.properties"
set "_param=Parameter=dev"
set "_base=baseURLvalue=https://prodweb-dev.net/start"
set "_url=url=/client/versions-6.0.1.xml"

for /f "tokens=*" %%a in ('type "%iofile%" ^| find /v /n "" ^& break ^> "%iofile%"') do (
     set "str=%%a
     set "str=!str:*]=!"
     if "!str:~0,9!"=="Parameter" set "str=%_param%"
     if "!str:~0,7!"=="baseURL" set "str=%_base%"
     if "!str:~0,3!"=="url" set "str=%_url%"
     >>%iofile% echo(!str!
  )

推荐阅读