【问题标题】:Windows Batch for-loop. Problems with doublequotesWindows 批处理 for 循环。双引号的问题
【发布时间】:2012-06-06 13:32:58
【问题描述】:

假设我想使用以下代码将文件从一个位置复制到另一个位置:

@set FILE=%1
@set SCRDIR=C:\test dir
@set DSTDIR=%SCRDIR%\temp

for %%f in ("%SCRDIR%\%FILE%") do @(
    echo Copying "%%f" to "%DSTDIR%"
    copy "%%f" "%DSTDIR%"
)

文件存在:

 C:\test dir>dir /b copyme.txt
copyme.txt

首先我用文件名作为我要复制的参数调用脚本:

C:\test dir>test.bat rename.txt

C:\test dir>for %f in ("C:\test dir\rename.txt") do @(
echo Copying "%f" to "C:\test dir\temp"
 copy "%f" "C:\test dir\temp"
)
Copying ""C:\test dir\rename.txt"" to "C:\test dir\temp"
The system cannot find the file specified..

上面的复制命令失败,因为多余的引号......

现在我使用包含通配符 * 的文件名调用脚本:

C:\test dir>test.bat copyme.*

C:\test dir>for %f in ("C:\test dir\copyme.*") do (
echo Copying "%f" to "C:\test dir\temp"
 copy "%f" "C:\test dir\temp"
)

C:\test dir>(
echo Copying "C:\test dir\copyme.txt" to "C:\test dir\temp"
 copy "C:\test dir\copyme.txt" "C:\test dir\temp"
)
Copying "C:\test dir\copyme.txt" to "C:\test dir\temp"
        1 file(s) copied.

在上面的例子中,我使用通配符,它​​工作得非常好。

谁能解释这种行为?当我不使用通配符时,为什么 Windows 会添加额外的引号?还是因为我使用通配符而省略了额外的引号? 为了处理包含空格的路径,我必须引用 FOR 循环的路径\文件名,因此不能省略这些。

【问题讨论】:

    标签: windows batch-file for-loop wildcard quotes


    【解决方案1】:

    当没有通配符时,for 命令不会检查文件是否存在,因此有效地将其名称视为字符串文字,包括引号。 只需使用"%%~f" 而不是"%%f"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      相关资源
      最近更新 更多