2

I have a Folder and some sub folders which contain a file with same file name but different values in it.I have to copy that files to a common folder but i want to keep all the files means i have to rename that files using batch file script in windows

Input Folder

D:\Data\Logs\Day1\DataLog.txt
D:\Data\Logs\Day2\DataLog.txt
D:\Data\Logs\Day3\DataLog.txt
D:\Data\Logs\Day4\DataLog.txt
D:\Data\Logs\Day5\DataLog.txt
D:\Data\Logs\Day6\DataLog.txt

Output Folder Like

D:\Data\Common\Logs\DataLog1.txt
D:\Data\Common\Logs\DataLog2.txt
D:\Data\Common\Logs\DataLog3.txt
D:\Data\Common\Logs\DataLog4.txt
D:\Data\Common\Logs\DataLog5.txt
D:\Data\Common\Logs\DataLog6.txt

i have tried this but its overwriting the existing file

pushd D:\Data\Logs
    for /r %%a in (*.*) do (
        COPY  "%%a" "D:\Data\Common\Logs\%%~nxa"
    )
popd
Hackoo
  • 18,337
  • 3
  • 40
  • 70
Jayesh
  • 39
  • 4
  • Take a look at this [How to Copy (and increment) Multiple Instances of a File Using Batch File](https://stackoverflow.com/questions/28697436/how-to-copy-and-increment-multiple-instances-of-a-file-using-batch-file?answertab=active#tab-top) – Hackoo May 30 '17 at 11:21
  • But the source folder have multiple sub folders. – Jayesh May 30 '17 at 11:38

1 Answers1

0

It's a bit more of a general approach, but you could try something like this:

setlocal enabledelayedexpansion
set "files=d:\data\logs\*.txt"
set "destDir=d:\data\common\logs"

for /f "delims=" %%f in ('dir "%files%" /b /s') do (
  for %%d in ("%destDir%\%%~nf*") do (
    set /a count+=1
  )
  xcopy "%%f" "%destDir%\%%~nf!count!%%~xf*"
  set count=
)

Due to delayed expansion, the last variant of the script is unable to handle files that contain carets (^) within their fully qualified path name.

When a command-line contains environment variables that are expanded at execution time (like the count variable in this script), the entire command-line seems to be parsed twice. The for-loop variables (%%f and variants thereof) will be expanded during the first parse, the count variable is expanded during the second parse. Because the for-loop variables are already expanded when the second parse takes place, any singular carets present in the values of the for-loop variables are swallowed by the parser and omitted from the final result.

Here is the revision of the script that should take care of the problem described:

setlocal enabledelayedexpansion
set "type=.txt"
set "source=d:\data\logs"
set "dest=d:\data\common\logs"

for /r "%source%" %%f in ("*%type%") do (
  for %%d in ("%dest%\%%~nf*") do (
    set /a count+=1
  )
  set "source=%%f"
  set "dest=%dest%\%%~nf"
  xcopy "!source!" "!dest!!count!%type%*"
  set count=
)
303
  • 2,417
  • 1
  • 11
  • 25