# Solved: Batch file: Copy, paste, rename, repeat



## JTS123 (Dec 4, 2012)

It would appear that in my efforts to find a solution to my problem I stumbled across another one of my posts asking a similar question. My current problem is very similar to what I had tried to solve before, but I don't know enough about reading the batch file to change it. (Reference)

I'm looking for a .txt file (actually, it's a .PAT file, but it's just a rename of a .txt file) in ~2000 folders. If there is a .txt file in the folder, I want to copy it to a single folder and rename it.

Server / file structure is similar to:
F:\123456\folder1\folder2\...\folderN\ABC0001.txt

Similar to my previous problem, this file needs to be renamed as the first folder it comes from. In this case, ABC0001.txt gets renamed as 123456.txt. Then it repeats for the next folder.

The catch: There are _lots_ of .txt files in each main folder. I'm looking for a specific set of them.
The helpful bit: Each file I'm looking for is named in a similar fashion to ABC0001.txt. Three letters (always ABC), four numbers (starting at either 0000 or 0001 and going up sequentially). Any other .txt file is garbage for me (typically four letters + four numbers).

So, good files:
ABC0000.txt
ABC0001.txt
ABC0002.txt
etc.

Bad files:
WXYZ0000.txt
WXYZ0001.txt
etc.

ABC will never be = WXYZ.

Summary:
Search F:\
Find F:\123456\folder1\ABC0001.txt
Ignore \WXYZ0001.txt
Copy to C:\Results\
Rename as 123456.txt
Repeat for next file

If there are multiple "good" files, rename them as 123456(1) ... (2)... etc.

Thanks again in advance. I hope this hasn't been too jumbled.

JTS


----------



## foxidrive (Oct 20, 2012)

EDITED: made the filenames match the spec more closely:

The duplicate files will be named as below in the order they are copied
but unique files will use the rootfoldername.ext format.

"rootfoldername(1).ext"
"rootfoldername(2).ext"
...
"rootfoldername(N).ext"

Test it on some samples first.


```
@echo off
setlocal EnableDelayedExpansion
set c=0
for /r "f:\" %%a in (ABC????.txt) do (
      for /f "tokens=2 delims=\" %%b in ("%%~fa") do (
        if exist "c:\results\%%b%%~xa" (
           set /a c+=1
           copy "%%a" "c:\results\%%b(!c!)%%~xa"
         ) else (
           copy "%%a" "c:\results\%%b%%~xa"
        )
  )
)
```


----------



## foxidrive (Oct 20, 2012)

_I changed the code above_


----------



## JTS123 (Dec 4, 2012)

Works wonderfully - thank you for your quick help again.


----------



## foxidrive (Oct 20, 2012)

Thanks, it's good to hear.

If you ever run this to add more files to the same folder, then you will need to change c=0 to something like c=100 where 100 is above the number which is already used in the recurring filenames inside the folder.


----------

