1

I have a for loop reading lines from a file called "temp". It should read each line and then proceed to create a directory for each name in the file. However, it's reading the first line of the file twice before it moves to the second line. So I get an error saying the folder already exists.

The file "temp" contains, for now, two entries:

folder1 
folder2

The code is simple:

for /F "tokens=*" %%i in  (temp) do  (
    set pstname=%%i
    echo the folder name is set to  %pstname%
    mkdir C:\output\%pstname%
)

When I run this, it reads the first line, folder1, from the "temp" file and creates the directory c:\output\folder1. So I expect that in the next iteration the variable pstname will be set to the second line in the "temp" file (should be set to folder2)

But that is not what happens. The loop reads fodler1 twice and attempts to create the folder1 folder again. If I continue with the script it eventually reads the second line from the "temp" file (folder2) and creates it. So the script almost works.

Issue: What am I doing wrong? It reads the first line in the file "temp" twice before it proceeds to the next line?

Is there a next command I have to use? What is wrong with my logic?

4

1 回答 1

2

再看一遍。未创建第二个目录。

你是“延迟扩张”问题的受害者。从虽然到右括号的整个命令FOR被解析,并且在那个时候,任何 %var% 都被替换var为在该行被解析时的值。只有这样,该行才被执行。

因此,运行一次你的 codefrag,并且pstname当时它被用作目标目录名称 - 可能是空的(如果没有其余的代码,就无法判断。)

因此执行的是(假设pstname为空)

for /F "tokens=*" %%i in  (temp) do  (
    set pstname=%%i
    echo the folder name is set to
    mkdir C:\output\
)

但是pstname将从文件的最后一行获取名称。

如果您然后再次运行代码而不pstname先清除,那么您将得到

for /F "tokens=*" %%i in  (temp) do  (
    set pstname=%%i
    echo the folder name is set to  folder2
    mkdir C:\output\folder2
)

这将被执行两次 - 每行一次temp- 并创建该目录。

SO上有很多关于这个问题的参考资料。最简单的治疗方法是

for /F "tokens=*" %%i in  (temp) do  (
    echo the folder name is set to  %%i
    mkdir "C:\output\%%i"
)

(注意要创建的名称周围的兔子耳朵 - 说明名称中的空格)

于 2013-09-13T05:12:41.250 回答