Shyam Sundar Kulkarni
Shyam Sundar Kulkarni

Reputation: 321

Copy files to destination with a backup - batch file

I am in need to a batch command, which will keep a backup of the files after copying to the destination.

Assume I have 2 files in source directory:

"1.txt" which has content (abc)  
"2.txt" which has content (abc)  

and I have 4 files in Destination Directory:

"1.txt" which has content (xyz)  
"2.txt" which has content (xyz)  
"5.txt" which has content (xyz)  
"6.txt" which has content (xyz)    

Now i have to copy all text files from source directory to destination directory, but in this case since the destination directory has two text files already present(1.txt and 2.txt) we need to take a backup of it before copying from source folder (maybe something like 1.txt.bkup 2.txt.bkup).

After copying from source to destination, contents of my destination should be:

"1.txt.bkup" which has content (xyz)  
"2.txt.bkup" which has content (xyz)  
"5.txt" which has content (xyz)  
"6.txt" which has content (xyz)  
"1.txt" which has content (abc)  
"2.txt" which has content (abc)    

How can this be done? Shyam

Upvotes: 0

Views: 1426

Answers (1)

Endoro
Endoro

Reputation: 37569

try this:

cd /d sourcefolder
for %%a in (*.txt) do (
    if exist "destinationfolder\%%~a" (
        move /y "destinationfolder\%%~a" "destinationfolder\%%~a.bkup"
    )
    copy "%%~a" "destinationfolder\%%~a"
)

Upvotes: 3

Related Questions