当前位置: 动力学知识库 > 问答 > 编程问答 >

windows - How to read from a .properties file using batch script

问题描述:

I have a requirement where i'd like to read values from a .properties file

my properties file test.properties content

file=jaguar8

extension=txt

path=c:\Program Files\AC

From the above file I need to fetch jaguar or anything after =

Please help me. Thanks

网友答案:

Try this

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
网友答案:
For /F "tokens=1* delims==" %%A IN (test.properties) DO (
    IF "%%A"=="file" set file=%%B
)

echo "%file%"

hope this could help

网友答案:
@echo off  
FOR /F "tokens=1,2 delims==" %%G IN (test.properties) DO (set %%G=%%H)  
echo %file%  
echo %extension%  
echo %path%

Note that there is no space after %%H. Else this causes a space to be appended, to file paths for example, and will cause file not found errors when the variables from the property files are used as part of a file path.Struggled for hours because of this!

网友答案:

A solution with support for comments (# style). See comments in code for explanation.

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

properties-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=
)

output from set test. (see above):

test.some.property=3
test.text=asd=f

The most important parts are:

  • the for-loop with the eol and delims option and
  • the if-checks that both variables %%a and %%b are set.

What you do in the for-loop with the variable and its value is certainly up to you - assigning to some prefixed variables was just an example. The namespacing approach avoids that any other global variable gets overridden. For example if you have something like appdata defined in your .properties file.

I'm using this to get rid of an extra config.bat and instead using one .properties file for both the java app and some support batch files.

Works for me, but certainly not every edge case is covered here, so improvements welcome!

分享给朋友:
您可能感兴趣的文章:
随机阅读: