批处理脚本 - 由两个或多个空格分隔

Batch script - split by two or more spaces

我有一个看起来像这样的大字符串

aa bb c d  f eeeee    ffff

我不确定字符串附带的 space 的数量。下一次,字符串可能在 aa 和 bb ansd 之间有五个 spaces 等等...

aa     bb     c      f       eee ff

有没有一种方法可以在批处理脚本中使用 delims 拆分两个或更多 spaces(spaces 的可变数量)?我总是想要第二个标记,无论任何 space在第一个和第二个标记之间。

PS : 编辑 我想要第二个令牌(令牌我的意思是在拆分两个或更多 spaces 之后获得的令牌)。我的令牌本身可以包含一个 space。示例:a b c d。 在此要提取b。 另一个例子: a b b c d 。 在此我想提取 b b.

未来读者须知:

此答案已发布 之前 OP 添加了重要文本 I always want the second token no matter how any spaces are there between first and second tokens.

请先阅读原题voting/commenting


没有

delims表示token被any sequence of any of the defined delimiter characters.

分隔

因此您的示例字符串将被处理为 7 个单独的标记。

如果您能告诉我们您正在尝试做什么,可能会有所帮助。采取的方法通常取决于预期的结果。

这可能与您尚未回复的 有关。

(从各种评论中收集:令牌由两个或多个空格分隔;您需要第二个令牌;每个令牌可能有也可能没有单个空格)

我评论了每一步并添加了一个 echo 来显示进度。

@echo off
setlocal 
set "string=ads ads      d b c    dsad   ds   ads"
echo 1: "%string%"
REM remove first token (delimited by ecactly two spaces):
set "string=%string:*  =%"
echo 2: "%string%"
REM remove leading spaces:
for /f "tokens=*" %%a in ("%string%") do set "string=%%a"
echo 3: "%string%"
REM remove third and next tokens (delimited by two or more spaces)
set string=%string:  =&REM %
echo 4: "%string%"

我对你之前问题的回答唯一的变化是for删除前导空格

如果有人感兴趣,我就是这样实现的。

@echo off

echo.
set "string=Admin State    State          Type             Interface Name"
echo Parse "%string%"

REM: Parse string delimited by more than one space
for %%R in ("%string:  =" "%") do (

    REM: Filter empty
    if not "%%~R" == "" (
        
        REM: Trim leading space
        for /f "tokens=*" %%a in ("%%~R") do set "part=%%a"
        call echo - "%%part%%"
    )
)

echo.
goto :eof

输出:

Parse "Admin State    State          Type             Interface Name"
- "Admin State"
- "State"
- "Type"
- "Interface Name"

我会这样做:

@echo off
setlocal 

set "string=ads ads       d b c    dsad   ds   ads"

set "tok1=%string:  =" & if not defined tok2 set "tok2=%"
for /F "tokens=*" %%a in ("%tok2%") do set "tok2=%%a"

echo "%tok2%"

如果您想了解使用的方法,请删除 @echo off 行并仔细查看执行的代码...