如何从批处理文件中读取属性文件

How to read properties file from batch file

我有一个很长的 test.properties 文件,在最顶部包含以下内容:

property1=cheese
property2=apple
property3=bread

# many more properties

我可以通过将工作目录更改为包含 test.properties 和 运行 的目录来从命令行读取这些属性,方法如下:

> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
    IF "%A"=="property1" SET firstitem=%B
> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
    IF "%A"=="property2" SET seconditem=%B

> echo %firstitem%
cheese
> echo %seconditem%
apple

但是,当我尝试将此代码放入存储在同一目录中的批处理文件时,它失败了,我无法弄清楚原因:

FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO 
    (IF "%A"=="property1" SET firstitem=%B)
FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO
    (IF "%A"=="property2" SET seconditem=%B)

运行 来自命令行的批处理文件给了我这个:

> "C:\folder\testbatch.bat"
~dp0\test.properties") DO IF "B was unexpected at this time.

如何使用批处理文件读取属性,以便将它们存储在可用于脚本其余部分的变量中?

编辑:问题已解决;下面的工作代码。

FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO 
    (IF "%%A"=="property1" SET firstitem=%%B)
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO
    (IF "%%A"=="property2" SET seconditem=%%B)

这里有两个问题:

  1. 在批处理文件版本中,迭代器变量需要 两个 个百分号。
  2. 在批处理文件版本中,您错误地将文件名用引号括起来,导致字符串本身被标记化,而不是字符串指定的文件的内容。 更新: @Stephan 正确地指出了使用 usebackq 修饰符以获得更通用的解决方案。但是既然你在谈论 "batch file stored in the same directory",你也可以完全删除路径前缀 %~dp0

更正版本:

@ECHO OFF
FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
    IF "%%A"=="property1" SET firstitem=%%B 
)
FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
    IF "%%A"=="property2" SET seconditem=%%B
)
ECHO %firstitem%
ECHO %seconditem%

Returns:

cheese
apple

"What can I do to read the properties using the batch file, so that they are stored in variables that can be used in the rest of the script?"

如果您愿意使用文件中的字符串,这对您来说非常简单:

FOR /F "usebackq tokens=*" %%A IN ("%~dp0\test.properties") DO set %%A
echo property2 is %property2%

注意:如果您的路径或文件名包含空格,则需要引号。用 usebackq

告诉 for 不要把它当作一个字符串