Windows 批处理脚本(使用多个分隔符分割字符串)

问题描述 投票:0回答:2

我有一个属性文件(test.properties),其中有一个保存多个字符串的变量。


例如:var=str1;str2;str3;.....

我需要在批处理文件(abc.bat)中使用上述属性文件,以便我可以逐行打印值。批处理文件的输出应该如下所示......


str1
str2
str3
...
...
(等等)

如有任何帮助,我们将不胜感激..谢谢:)

我尝试使用“for循环”以这种方式将值与第一个分隔符(=)分开......

IF EXIST "test.properties"
(
    ECHO test.properties file found
    for /F "tokens=1,2 delims==" %%A IN (test.properties) DO
    (
        set value="%%B"
        ECHO !value!
    ) 
)
Output=str1;str2;str3;....

现在如果我想解析“!value!”中的字符串我逐行使用...

for /F "tokens=* delims=;" %%x IN ("!value!") DO
(
    ECHO %%x
)

我遇到错误......有什么帮助吗?

windows batch-file
2个回答
1
投票

只需使用普通的

for
来获取列表的元素(
;
是标准分隔符)

@echo off
setlocal enabledelayedexpansion

>test.properties echo var=str1;str2;str3;str4;str5;str6

IF EXIST "test.properties" (
    ECHO test.properties file found
    for /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
        set "value=%%B"
        ECHO !value!
    ) 
    for %%x IN (!value!) DO echo %%x
)

0
投票

for /F "tokens=* delims=;" %%x IN ("!value!")
命令不会执行您希望它执行的操作。

它不会在每个分号分隔符

value
处拆分
delim=;
变量中的字符串,并执行循环体,并将
%%x
设置为每个结果子字符串。

for /F
命令将在文件中的每行迭代一次,并从该行中提取 1 个或多个值。它为文件中的每一行运行一次循环体中的代码。

当您在带引号的字符串上使用

for /F
时,它会将该字符串视为文件中的单行。它将从该字符串中提取 1 个或多个值,但只会运行循环体中的代码一次。

这是一个有效的批处理脚本

@SetLocal EnableExtensions
@echo off

@rem Default Values Go Here
set sDEFAULT_PROP_FILE_PATH=%temp%\test.properties

@rem Get the path to the properties file from the command line
set sPropFilePath=%~1

@rem If the caller did not specify a properties file, assume the default;
if "%sPropFilePath%" EQU "" (
    @echo INFO: Using default properties file:  "%sDEFAULT_PROP_FILE_PATH%"
    set sPropFilePath=%sDEFAULT_PROP_FILE_PATH%
)

@rem If the properties file does not exist then give up.
if not exist "%sPropFilePath%" (
    @echo ERROR: properties file not found:  "%sPropFilePath%"
    goto :EOF
)

@rem Extract the property name and value.
for /F "tokens=1,2 delims==" %%A in (%sPropFilePath%) do (
    set sPropertyName=%%A
    set sPropertyValue=%%B
)

@rem Show property name and value extracted
@echo Property File: %sPropFilePath% contains:
@echo %sPropertyName% = %sPropertyValue%
@echo ----

@rem Repeatedly extract string before first delimiter
set sRemainder=%sPropertyValue%;
:LoopBegin
    for /F "tokens=1,* delims=;" %%A IN ("%sRemainder%") DO (
        set sExtracted=%%A
        set sRemainder=%%B
    )
    @echo.%sExtracted%
    if "%sRemainder%" NEQ "" goto :LoopBegin
:LoopEnd

@echo ----

该脚本的工作原理是重复从剩余属性字符串中提取两个值:要显示的字符串和下一个剩余属性字符串。

开始

sRemainder
设置为完整属性值
"str1;str2;str3,...;strN"

提取的两个值是:

  1. sExtracted
    :第一个分号之前的子字符串:
    "str1"
  2. sRemainder
    :第一个分号之后的所有内容:
    "str2;str3;...;strN"

脚本循环回来,但现在

sRemainder
"str2;str3;...;strN"
,所以提取的两个值是:

  1. sExtracted
    :第一个分号之前的子字符串:
    "str2"
  2. sRemainder
    :第一个分号之后的所有内容:
    "str3;...;strN"
© www.soinside.com 2019 - 2024. All rights reserved.