Search code examples
batch-filecopytext-files

batch script to copy files listed in a txt document and keep duplicates


I am trying to copy thousands of image files listed in a text file from multiple folders to one folder. The script I have works if all the file names were different. How do I get it to rename duplicates or rename all of them? Either will work as the name isn't important.

Example list

G:\research_data\an\an01\DCIM\100MSDCF\DSC04450.JPG
G:\research_data\an\an01\DCIM\100MSDCF\DSC04076.JPG
G:\research_data\an\an01\DCIM\100MSDCF\DSC03141.JPG
G:\research_data\an\an01\DCIM\120MSDCF\DSC04840.JPG
G:\research_data\an\an02\DCIM\100MSDCF\DSC04450.JPG
G:\research_data\an\an02\DCIM\112MSDCF\DSC04076.JPG
G:\research_data\an\an03\DCIM\102MSDCF\DSC03141.JPG
G:\research_data\an\an03\DCIM\105MSDCF\DSC04450.JPG
G:\research_data\an\an03\DCIM\106MSDCF\DSC04076.JPG

code:

@echo off
for /f "tokens=* delims=" %%a in ('type "L:\an_2017\image_list.txt"') do xcopy /hrkvy "%%a" "L:\an_2017"
pause

Solution

  • I see the issue you're running into. Looks like you're trying to transfer images from various directories with some containing the same file names. If you wish to keep both files, you could use an FOR statement to read your text file and rename the file at hand to DSC{Count} from 1+.

    Using enabledelayedexpansion we can use set /a count += 1 to count up one number and rename %%a to a number. Please keep in mind I'm using %%~xa to get the extension of each file from the textfile. More info here: Parameter Extensions

    The script bellow will read all file locations in the image_list.txt file and will copy each item to it's target directory with a new name of DSC1-DSCinfinity based on how many items are in image_list.txt. This avoids any issue's with duplicate names in your text file.

    @ECHO OFF
    @setlocal enableextensions enabledelayedexpansion
    
    rem configure directories
    set "source=L:\an_2017\image_list.txt"
    set "target=L:\an_2017"
    
    rem rename files to DSC{Count}
    set /a count = 1
    for /f "tokens=* delims=" %%a in ('type "%source%"') do (
    
    copy "%%a" "%target%\DSC!count!%%~xa"
    set /a count += 1
    
    )
    
    goto :EOF