Windows – Command/script to copy files with certain ext, which may have the same name, from folder structure to singe directory and rename

command linewindows

From a source directory structure (multiple folders), I need to copy all csv files to a single target directory. I found a command to do this, though files of the same name exist within different folders of the source structure, causing obvious issues when copied to one folder.

How can the files with duplicate names be renamed during the copy please (ideally: report.csv, reportcopy2.csv etc)? The job currently only copies a single instance of each file. Thanks for help.

Best Answer

This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.

I would suggest you rename on copy to something like Foldername.Filename.csv.

Use something like

echo f | xcopy /f /y srcfile destfile

EDIT

I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.

This is what I have

set sDir=C:\Documents and Settings\drook\Desktop
set dDir="C:\Documents and Settings\drook\Desktop\Folder\"

cd C:\Documents and Settings\drook\Desktop\
FOR /F %%a in ("*.txt") DO (     
    xcopy "%%a" "C:\Documents and Settings\drook\Desktop\Folder\"
    cd\ 
    cd C:\Documents and Settings\drook\Desktop\Folder\
    ren "%%a" "newName-%dir%.txt"
    cd\
    cd C:\Documents and Settings\drook\Desktop\
)

pause

It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...

Sorry, I don't think it is possible.

Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates

Related Question