这是在Windows批处理的错误? [英] Is this a bug in windows batch?

查看:120
本文介绍了这是在Windows批处理的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发现批处理脚本的一个奇怪的问题,我似乎无法解释。也许只是因为我不太了解批量工作的基础,但是这里是一个批处理文件(test.bat)的例子:

 <$ c (
echo $%$ j


FOR / Ftokens = 1 *%% $ b

如果我这样称呼它:

<$ p $ b> test.bat ab a,ba,b

得到这个作为我的输出:

  a,bab

为什么第二个逗号被剥离?如果我像这样转义逗号:

  test.bat ab a,ba ^,b

我得到正确的输出:

  a,ba,b

几乎和','一样由for循环分隔符,但是当我看FOR / ?,唯一的默认delim是白色空间。逗号不被列为分隔符。如果我明确指出delim是一个空格,我仍然会得到这个行为。如果我逃避报价,我仍然得到这种行为。不管怎样,如果逗号是分号,那么第一个逗号也应该被剥离出来吗?奇怪的是,如果你尝试在for循环中使用'usebackq',你会得到相反的结果。第一个逗号被删除,第二个被保留:

  aba,b

为什么我必须在引号内跳过所有逗号才能使用?是否有一些whindows规则,我失踪了,或者它只是在Windows批处理脚本中的错误?

解决方案

  @ECHO OFF 
SETLOCAL ENABLEDELAYEDEXPANSION
SETline = aba,ba,b
SET line
ECHO [%* ]
FOR / ftokens = 1 *%% i IN(%*)DO(ECHO %% j)
FOR / ftokens = 1 *%% i IN %line%)DO(ECHO %% j)
FOR / ftokens = 1 *%% i IN(!line!)DO(ECHO %% j)
FOR / f tokens = 1 *%% IN('echo%line%')DO(ECHO %% j)

GOTO:EOF

运行上述可能会指出一个解释。这完全是一个历史的问题 - 相当当一个替代 - %var%首先,%% x秒和!var!第三。


I have found a peculiar issue with batch scripting that I cannot seem to explain. Maybe its just because I do not know enough about the underpinnings of how batch works but here is an example batch file (test.bat):

@echo off

FOR /F "tokens=1*" %%i in ("%*") DO (
    echo %%j
)

if I call it like so:

test.bat ab a,b "a,b"

I get this as my output:

a,b "a b"

Why was the second comma stripped out? If I escape the comma like so:

test.bat ab a,b "a^,b"

I get the correct output:

a,b "a,b"

It is almost like ',' is considered a delimiter by the for loop, but when I look at FOR /?, the only default delim is white space. Comma is not listed as a delim. If I specifically state that the delim is a space, I still get this behavior. If I escape the quotes, I still get this behavior. Anyways, if comma was a delim, the first comma should also be stripped out right?. Oddly enough if you try to use 'usebackq' with the for loop, you get the exact opposite. The first comma is stripped out and the second one is preserved:

a b "a,b"

Why do I have to escape all commas inside quotes for this to work? Is there some whindows rule I am missing or is it just a bug in windows batch scripting?

解决方案

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "line=a b a,b "a,b""
SET line
ECHO [%*]
FOR /f "tokens=1*" %%i IN ("%*") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ("%line%") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ("!line!") DO (ECHO %%j)
FOR /f "tokens=1*" %%i IN ('echo %line%') DO (ECHO %%j)

GOTO :EOF

Running the above may point to an explanation. It's all a matter of history - quite when a substitution is made - %var% first, %%x second and !var! third.

这篇关于这是在Windows批处理的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆