2

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.

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"

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

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

3
  • 1
    How will you deal with filename collisions if two files with the same name exist in different folders? Commented Oct 9, 2014 at 5:50
  • FOR /F quoted options cannot use FOR variables or delayed expansion. It has to do with the order in which various parsing phases take place. Commented Oct 9, 2014 at 11:50
  • @foxidrive There should not be collisions (at least for what I'm doing now), so I didn't think about how to deal with it. Anyway if I need to do it I think the best way will be to transform the path to the file to it's name. Commented Oct 15, 2014 at 19:56

2 Answers 2

3
@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
        )
    )

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

Sign up to request clarification or add additional context in comments.

Comments

1

You could achieve this by calling a subroutine instead of nesting the loops. Something like:

for /f %%u in (user.txt) do call :doxcopy %%u
goto :eof

:doxcopy
for /r "C:\Folder\%1" %%f in (*.*) do @xcopy "%%f" "C:\Folder 2\%1" 
goto :eof

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.