处理for / f

时间:2017-06-07 17:14:17

标签: windows batch-file path escaping filepath

更新:for /f行无问题。在我的原始代码中,我在回显它时没有将%~2括在引号中,如下所示:echo.%%f only in %~2。我只是忘了整个for /f被同时解析,所以我忽略了其他可能的原因,包括这个实际原因。

在(递归)子例程中,我有:

echo.I really hate this problem: %~2
for /f "usebackq delims=|" %%f in (`dir /b "%~2"`) do (
    echo.Breaks before this echo

其中%~2 = d1 test\same1\fldr (break)\broken作为测试用例

输出:

I really hate this problem: d1 test\same1\fldr (break)\broken
\broken was unexpected at this time.

我认为错误(输出的第二行)是因为)中的d1 test\same1\fldr (break)\broken充当((`dir /b "%~2"`)的右括号

另外,我在子例程中多次引用%~2,包括在for /f内部,所以如果可能的话,我真的需要一个更通用的解决方案。

所以问题是:当%~2包括括号时,如何强制(`dir /b "%~2"`) %~2的预期解释?

修改

好的,我使用基于我的真实代码的小测试文件重现了相同的输出。这就是让我意识到echo导致问题的for /f的原因。请参阅本文顶部的更新。

test.bat的:

echo
call :testSub isMismatch "d1 test\same1\fldr (break)\broken" "d2 test\same1\fldr (break)\broken"
pause
goto:eof

:testSub
echo.I really hate this problem: %~2
for /f "usebackq delims=|" %%f in (`dir /b "%~2"`) do (
    echo.%%f only in %~2
)

输出:

G:\broken>test.bat

G:\broken>echo
ECHO is on.

G:\broken>call :testSub isMismatch "d1 test\same1\fldr (break)\broken" "d2 test\same1\fldr (break)\broken"

G:\broken>echo.I really hate this problem: d1 test\same1\fldr (break)\broken
I really hate this problem: d1 test\same1\fldr (break)\broken
\broken was unexpected at this time.

G:\broken>      echo.%f only in d1 test\same1\fldr (break)\broken

G:\broken>

0 个答案:

没有答案