如何使用批处理脚本从.properties文件中读取

13 windows batch-file

我有一个要求,我想从.properties文件中读取值

我的属性文件test.properties内容

file=jaguar8
extension=txt
path=c:\Program Files\AC
Run Code Online (Sandbox Code Playgroud)

从上面的文件中我需要获取jaguar或之后的任何内容=

请帮我.谢谢

小智 24

For /F "tokens=1* delims==" %%A IN (test.properties) DO (
    IF "%%A"=="file" set file=%%B
)

echo "%file%"
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


小智 18

@echo off  
FOR /F "tokens=1,2 delims==" %%G IN (test.properties) DO (set %%G=%%H)  
echo %file%  
echo %extension%  
echo %path%
Run Code Online (Sandbox Code Playgroud)

请注意,%% H之后没有空格.否则,这会导致将空间附加到文件路径,例如,当属性文件中的变量用作文件路径的一部分时,将导致文件未找到错误.由于这个原因,因此需要几个小时!


abi*_*964 6

试试这个

echo off
setlocal
FOR /F "tokens=3,* delims=.=" %%G IN (test.properties) DO ( set %%G=%%H )

rem now use below vars
if "%%G"=="file"
 set lfile=%%H
if "%%G"=="path"
 set lpath=%%H
if "%%G"=="extension"
 set lextention=%%H
echo %path%

endlocal
Run Code Online (Sandbox Code Playgroud)


小智 6

支持评论的解决方案(#style).请参阅代码中的注释以获取解释

test.properties:

# some comment with = char, empty line below

#invalid.property=1
some.property=2
some.property=3
# not sure if this is supported by .properties syntax
text=asd=f
Run Code Online (Sandbox Code Playgroud)

属性 - read.bat:

@echo off

rem eol stops comments from being parsed
rem otherwise split lines at the = char into two tokens
for /F "eol=# delims== tokens=1,*" %%a in (test.properties) do (

    rem proper lines have both a and b set
    rem if okay, assign property to some kind of namespace
    rem so some.property becomes test.some.property in batch-land
    if NOT "%%a"=="" if NOT "%%b"=="" set test.%%a=%%b
)

rem debug namespace test.
set test.

rem do something useful with your vars

rem cleanup namespace test.
rem nul redirection stops error output if no test. var is set
for /F "tokens=1 delims==" %%v in ('set test. 2^>nul') do (
    set %%v=
)
Run Code Online (Sandbox Code Playgroud)

输出set test.(见上文):

test.some.property=3
test.text=asd=f
Run Code Online (Sandbox Code Playgroud)

最重要的部分是:

  • for与-loop eoldelims选项
  • - if检查两个变量%%a%%b设置.

你在for-loop中使用变量及其值做什么肯定取决于你 - 分配给一些前缀变量只是一个例子.命名空间方法避免了任何其他全局变量被覆盖.例如,如果您appdata在.properties文件中定义了类似的内容.

我正在使用它来摆脱额外的config.bat,而是使用一个.properties文件用于Java应用程序和一些支持批处理文件.

适合我,但肯定不是每个边缘案例都在这里,所以欢迎改进!