批处理文件,以一个类型的所有文件移动到不同的驱动器保持原有的目录树 [英] batch file to move all files of a type to a different drive maintaining the original directory tree

查看:160
本文介绍了批处理文件,以一个类型的所有文件移动到不同的驱动器保持原有的目录树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到的最接近使用命令MV,这显然不是Windows命令。 Windows的移动命令不会做的工作。

The closest thing I have seen here uses a command "mv" which apparently is not a Windows command. Windows "Move" command won't do the job.

我有一个文本文件,该文件列出了需要移动显示从C完整路径文件中的每一个:\\(例如C:\\ DI1 \\ DIR2 \\ DIR3 \\ dir4 \\ filetomove.png。
一些子目录的名称中都有空间,没有标准命令。有些可能是一个层次深,其他5级。

I have a text file which lists every one of the files that needs to be moved showing its full path from c:\ (example C:\di1\dir2\dir3\dir4\filetomove.png. Some of the sub-directory names have spaces in them and there is no standard order. Some may be one level deep with others 5 levels deep.

我想做到这一点,这样我结束了一个新的列表是完全一样的老除了盘符是X:\\代替C:\\

I would like to do this such that I end up with a new list that is exactly the same as the old except that the drive letter would be X:\ instead of C:\

有在这些相同的目录中的许多其他的文件和它们不应该被触摸。只有那些在我一起工作的清单。

There are many other files in these same directories and they should not be touched. Only those in the list I am working with.

推荐答案

事实上,的Robocopy 的更加灵活,不易出错,但这里的一些批处理code读取文本文件和每行(假设每个文件的完整路径移动是行上):

Indeed, Robocopy is more flexible and less error prone, but here's some batch "code" that reads the text file and for each line (assuming that the full path of every file to be moved is on a line):


  • 计算目标文件夹(其实是将文件的父文件夹的第一个字符 - 这应该是驱动器盘符 - 用一个保存在 DESTINATION_DRIVE

  • 测试,如果新的父目录存在,如果不是创建它(和所有中介迪尔斯) - 这就是为什么移动命令用于失败:由于目标父目录并不存在。这里的说明:如果具有相同名称的文件作为目标目录存在,移动操作将明显失败

  • 执行移动操作

  • "calculates" the destination folder (actually replaces the 1st character of the file's parent folder - that should be the drive letter - with the one stored in DESTINATION_DRIVE)
  • tests if the new parent dir exists, and if not it creates it (and all intermediary dirs) - this is why the move command used to fail: because the destination parent dir didn't exist. A note here: if a file with the same name as the destination dir exists, the move operation will obviously fail
  • performs the move operation

脚本:

@echo off
set DESTINATION_DRIVE=e

for /f "tokens=*" %%f in (files.txt) do (
    call :move_file "%%f"
)
goto :eof

:move_file
    set _SRC_DIR=%~dp1
    set _DST_DIR=%DESTINATION_DRIVE%%_SRC_DIR:~1%
    if not exist "%_DST_DIR%\nul" (
        mkdir "%_DST_DIR%"
    )
    move %1 "%_DST_DIR%" 
    goto :eof

作为一个缺陷,移动文件后,该脚本可能会留下空迪尔斯源驱动器上。

As a flaw, after moving the files, the script might leave empty dirs on the source drive.

这篇关于批处理文件,以一个类型的所有文件移动到不同的驱动器保持原有的目录树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆