批处理文件选择性地将文件复制到相同的文件夹树

时间:2015-01-09 16:23:20

标签: batch-file

我有两个相同的文件夹树,我们称之为C:\FirstC:\Second,包含许多子文件夹。 C:\First在许多子和子子文件夹中有许多XML文件。 C:\Second只创建了文件夹树。

我想浏览C:\First\*中的所有XML文件,并将其放在C:\Second中的等效位置。

但首先我要检查C:\Current文件夹中是否存在具有相同名称的文件(没有子文件夹),在这种情况下,我会将C:\Current中的文件复制到正确的子文件夹中C:\Second中的子子文件夹。

换句话说,我想将整个结构和文件从C:\First复制到C:\Second,但我想采用C:\Current中可能存在或不存在的最新版本。并且,在C:\Current中有许多我不关心的文件。

实施例: C:\Current包含以下文件:

a.xml
b.xml
1.xml
c.xml
d.xml
e.xml
2.xml
f.xml
g.xml
3.xml

C:\Firsta.xml, b.xml, c.xml, d.xml, e.xml, f.xml, g.xml已在其子文件夹中展开。

我希望我不要太困惑......

1 个答案:

答案 0 :(得分:1)

当问题被正确陈述时,相同的问题描述可以作为编写程序的规范。在您的情况下,您有这样的描述:

  

我想浏览C:\ First *中的所有XML文件并将其放入其中   相当于C:\ Second的地方。

     

但首先我要检查一下是否存在同名文件   C:\当前文件夹

"但首先"没有用来编写程序。你只需要先写下第一件事!例如:

  

我想查看C:\ First *中的所有XML文件。我想检查一下   在这种情况下,C:\ Current文件夹中存在具有相同名称的文件   我将从C:\ Current复制到正确的子子文件夹   在C:\第二。否则将文件从C:\ First放入其中等效   放在C:\ Second。

以下伪代码是原始问题描述如何转换为程序的示例:

rem I have 2 identical folder trees, let's call them C:\First and C:\Second, with many subfolders.
rem C:\First has many XML files in many sub and sub-sub folders. C:\Second just has the folder tree created.

rem I want to go through all XML files in C:\First\* 
for /R inside C:\First with all *.XML files do (
   rem But first I want to check if a file with the same name exists in the C:\Current folder (no subfolders there)
   if exist "C:\Current folder\place here just the name of the file from the for command" (
      rem in which case I will copy the one from C:\Current to the proper sub-sub-sub folder in C:\Second.
      set properFolder=place here the sub-sub-sub folder from the for command
      set properFolder=change "C:\First" by "C:\Second" in properFolder
      copy "C:\Current folder\just the name" "!properFolder!"
   ) else (
      rem ... and put it in it's equivalent place in C:\Second. 
      set properFolder=place here the sub-sub-sub folder from the for command
      set properFolder=change "C:\First" by "C:\Second" in properFolder
      copy "the file from for command" "!properFolder!"
   )
)

如果你分析这段代码,你会发现获得properFolder的行在两个部分都是相同的,所以一个更简单的方法是在if命令之前只使用一次rightFolder。

您可以使用此伪代码作为编写批处理文件的起点。