开发者

Batch script - Ignore hash when reading lines from a file

I would like to set variables from name value pairs in a properties. The property file has # for comments

====sample input file=====

#This is a comment
### Another comment
appNames=HelloWorldApp
targetServer=serverABC

DEV.key1=value1
TEST.key2=value2

========= I have 2 issues

1)

C:\temp\dos>for /f "delims=" %i in (test.properties) do @set %i
Environment variable #This is a not defined
Environment variable ### Another not defined

Variables are set, but I would like comments to be ignored. I would like to do this with a single line of code, but get this instead.

for /f "delims=" %i in (test.properties) do @echo %i | find "#">nul || @set %i
find: unable to access "#": The system cannot find the file specified.
The process tried to write to a nonexistent pipe.
Environment variable #This is a not defined
find: unable to access "#": The system cannot find the file specified.
The process tried to write to a nonexistent pipe.

2) I would like this properties file to be passed as an argument to a batch script.Contents of the test.bat file

set propFilePathAndName=%1
for /f "delims=" %i in (%propFilePathAndName%) do echo %i

output

C:\temp\dos>set propFilePathAndName=/temp/dos/test.properties
propFilePathAndNamei was unexpected at this time.    

If I run the contents of this file one 开发者_如何转开发line at a time , it works. What am I doing wrong? Thanks in advance


To ignore lines starting with a hash, you could use the eol parameter of the for loop.
for /f "eol=# delims=" %i in (test.properties) do @set %i

The second issue is to double the percent inside of a batch file.

set propFilePathAndName=%1
for /f "delims=" %%i in (%propFilePathAndName%) do echo %%i

This is caused by the parser, there are different rules for the command line and batch files.

cmd-line
for %a in (xyz) do echo %a

batch-file
for %%a in (xyz) do echo %%a

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜