嵌套的FOR循环中的变量

嵌套的FOR循环中的变量

本文介绍了Windows批处理文件-嵌套的FOR循环中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件(users.txt)中有一个用户列表,我想为每个用户复制其目录(c:\ Folder \ username )中的每个文件,然后子目录位于另一个没有子目录的目录中(c:\ Folder 2 \ username ).

I've a list of users in a text file (users.txt) and I want, for each user, to copy every file in their directory (c:\Folder\username) and subdirectory in another directory without subdirectory (c:\Folder 2\username).

我现在正在使用包含以下内容的批处理文件:

I'm now using a batch file containing something like this:

for /f %%u in (user.txt) do (
    for /r "C:\Folder\%%u" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%%u"
)

...但是不起作用.

...but is not working.

经过一些测试,我能够找出问题所在:第二个FOR中的第一个%% u变量

After some tests I was able to find out what's wrong: the first %%u variable in the second FOR

for /r "C:\Folder\%%u" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%%u"

没有正确地替换为 username .
而是用它的值正确替换了第二个%% u(在DO命令中).

is not correctly replaced by the username.
Instead the second %%u (inside the DO command) is correctly replaced by it's value.

是否可以强制第一个%% u变量采用正确的值?

Is there a way to force the first %%u variable to take the correct value?

推荐答案

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f %%u in (user.txt) do (
        pushd "C:\Folder\%%u" && (
            for /r %%f in (*) do @xcopy /i /y "%%f" "c:\Folder 2\%%u\"
            popd
        )
    )

一个简单的解决方案是从第二个for

One simple solution is to remove the first for replaceable parameter from the recurse clause of the second for

这篇关于Windows批处理文件-嵌套的FOR循环中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:40