Windows CMD批处理:具有DelayedExpansion的FOR/R [英] Windows CMD Batch: FOR /R with DelayedExpansion

查看:147
本文介绍了Windows CMD批处理:具有DelayedExpansion的FOR/R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的桌面上,有一个名为"test" 的文件夹.此文件夹中有两个文件,分别是"file1.txt" "file2.txt" .

On my desktop, there is a folder named "test". Inside this folder is two files, "file1.txt" and "file2.txt".

看看这个简单的批处理脚本:

Take a look at this simple batch script:

@ECHO OFF

SET test="C:\Users\Tyler\Desktop\test"

ECHO %test%
FOR /R %test% %%F IN (*) DO (
    ECHO %%F
)

如您所料,它将输出以下内容:

As you might expect, it outputs the following:

"C:\Users\Tyler\Desktop\test"
C:\Users\Tyler\Desktop\test\file1.txt
C:\Users\Tyler\Desktop\test\file2.txt

现在看看这种变化:

@ECHO OFF

SETLOCAL ENABLEDELAYEDEXPANSION

SET test="C:\Users\Tyler\Desktop\test"

ECHO !test!
FOR /R !test! %%F IN (*) DO (
    ECHO %%F
)

ENDLOCAL

我希望它的输出没有什么不同.但是,这里是:

I would expect its output to be no different. However, here it is:

"C:\Users\Tyler\Desktop\test"

似乎!test!ECHO !test!行中扩展了,但在FOR /R !test!行中没有扩展,只是成为了!test!.因为那当然不是有效路径,所以FOR/R循环永远不会迭代.

It appears that !test! gets expanded in the ECHO !test! line, but not in the FOR /R !test! line, becoming just !test!. Since that is, of course, not a valid path, the FOR /R loop never iterates.

这是为什么?我想念什么?

Why is this? What am I missing?

推荐答案

FOR之所以与ECHO不同,是因为批处理解析器(cmd.exe)具有特殊的

Why FOR works different than ECHO is because the batch parser (cmd.exe) has special parsing rules for FOR, IF and REM.

因此,延迟扩展不适用于此处的参数,仅适用于括号内的参数.

Therefore delayed expansion doesn't work for the parameters here, only for the arguments inside the parenthesis.

只有百分比扩展适用于参数,因为解析器在切换到特殊的FOR解析器规则之前会执行百分比扩展阶段.

Only percent expansion works for the parameters, as the parser executes the percent expansion phase just before it switches to the special FOR parser rules.

如果您不能使用百分比扩展,那么您可以将代码移动到自己的函数中并对其进行调用.

If you can't use percent expansion, as you are inside of a block you can move the code to an own function and call it.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET test="C:\Users\Tyler\Desktop\test"

ECHO !test!
call :doMyLoop test
exit /b

:doMyLoop
set "arg=!%1!"
FOR /R %arg% %%F IN (*) DO (
    ECHO %%F
)

这篇关于Windows CMD批处理:具有DelayedExpansion的FOR/R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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