使用备份 - 批处理文件将文件复制到目标

时间:2013-07-26 08:38:57

标签: windows batch-file cmd directory

我需要一个批处理命令,它会在复制到目标后保留文件的备份。

假设源目录中有2个文件:

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

我在目的地目录中有4个文件:

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

现在我必须将所有文本文件从源目录复制到目标目录,但在这种情况下,由于目标目录已经存在两个文本文件(1.txt和2.txt),我们需要先备份它从源文件夹复制(可能类似于1.txt.bkup 2.txt.bkup)。

从源复制到目的地后,目的地的内容应为:

"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)    

如何做到这一点? 希亚姆

1 个答案:

答案 0 :(得分:3)

试试这个:

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