前言
我只是想为未来的读者添加这个,因为我遇到了这个问题,我自己解决了它,我认为仅仅展示如何简单地做到这一点会很有用。首先,dbenham
他的回答是绝对正确的,“不,你不能指定 2 个空格作为分隔符。” . 由于您不能直接使用批处理 for 循环来执行此操作,因此您可以简单地制作自己的来完成这项工作。再次dbenham
是正确的说法
“您可以使用 SET 搜索和替换将 2 个空格更改为某个唯一字符”
这与我所做的有点相似(有一些差异),但为了完整起见,我认为将其记录在案是件好事。问题是,简单地将所有出现的双空格设置为其他字符并不总能解决问题。有时我们有两个以上的空格,而我们真正想要的是用多个空格分隔字符串。我试图在这里解决的问题更像这样(来自 OP)Ricky Payne
“另一种可能更好的方法可能是使用特殊字符(即从未在进程或路径中使用的)复制多个空间的所有实例,然后将其用作我的分隔符......虽然我不知道如果这是可能的话..”
答案是这是可能的,而且一点也不难。你所需要的只是能够
A. 遍历字符串的每个字符
B. 区分单空格和双(或更多)空格
C. 遇到双空格时打开标志
D. 将双(或更多)空格转换为可以分隔的特殊字符或字符序列。
编码
为此,我编写了代码供自己使用(为清晰起见进行了编辑):
FOR /F "tokens=* delims=*" %%G IN ('<command with one line output>') DO (SET
"LineString=%%G")
SET /A "tempindex=0"
:LineStringFOR
SET "currchar=!LineString:~%tempindex%,1!"
IF "!currchar!"=="" (goto :LineStringFOREND)
SET /A "tempindex=!tempindex!+1"
SET /A "BeforeSpacePosition=!tempindex!"
SET /A "AfterSpacePosition=!tempindex!+1"
IF NOT "!LineString:~%BeforeSpacePosition%,2!"==" " (goto :LineStringFOR)
:LineStringSUBFOR
IF "!LineString:~%BeforeSpacePosition%,2!"==" " (
SET LineString=!LineString:~0,%BeforeSpacePosition%!!LineString:~%AfterSpacePosition%!
GOTO :LineStringSUBFOR
) ELSE (
SET LineString=!LineString:~0,%BeforeSpacePosition%!;!LineString:~%AfterSpacePosition%!
GOTO :LineStringSUBFOREND
)
:LineStringSUBFOREND
GOTO :LineStringFOR
:LineStringFOREND
ECHO Final Result is "!LineString!"
因此,如果您的输入(FOR 中命令的输出,或者您可以更改该 FOR 循环以接收字符串)是:
"abcab c"
输出应采用以下格式:
“a;b;c;ab c”
我已经在我自己的代码上对此进行了测试。但是,对于我在这里的回答,我删除了所有评论并更改了一些变量名称以清楚起见。如果在输入命令后此代码不起作用,请随时告诉我,我会更新它,但它应该可以工作。在此处格式化可能会阻止直接复制粘贴。
只是为了展示实际发生的事情
程序流程基本上是这样的:
FOR each character
:TOP
grab the next character
set a variable to the current index
set another variable to the next index
IF this or the next character are not spaces, goto the TOP
:Check for 2 spaces again
IF this and the next character are both spaces then
get the string up to (but not including) the current index AS A
get the string after the current index AS B
set the string to A+B
goto Check for 2 spaces again
ELSE we have turned the double or more space into one space
get the string up to (but not including) the current index AS A
get the string after the current index AS B
set the string to A + <char sequence of choice for delimiting> + B
goto TOP to grab the next character
After all characters are looped over
RETURN the string here (or echo it out like I did)
额外的
dbenham
在他对这种方法的回答中说:
“您可以使用 SET 搜索和替换将 2 个空格更改为某个唯一字符,但确定一个永远不会出现在您的描述或命令行中的唯一字符说起来容易做起来难。”
虽然这在过去可能是正确的,但我承认(至少对于我的方法,如果我在其他情况下错了,请纠正我)你实际上可以使用一个绝对不会出现在你的输入中的分隔符。这是通过使用多字符分隔符来完成的。这不允许您使用标准的 FOR 循环,但是您可以很容易地手动执行此操作。此处对此进行了更深入的描述:
"delims=#+#" - 超过 1 个字符作为分隔符