繁体   English   中英

使用源文件夹作为名称将文件从源目录树复制到新位置

[英]Copy file from source directory tree to new location using source folder as name

我有一个文件和文件夹目录,例如:

\Parent
|-\Child
||-\Test
|||-\Content
|||-targetfile.ext.out
|-\AnotherChild
||-anothertargetfile.ext.out

我想将任何具有.ext.out的文件复制到另一个目录,但要使用目录结构对其进行重命名。

EG:targetfile.ext.out将被复制到名称为“ ParentChildTestContent.ext.out”的已定义目录中,而“ anothertargetfile.ext.out”将被复制到与“ AnotherChild.ext.out”相同的已定义目录中。 为了简化脚本,可以删除.out。

只要文件夹结构的深度不超过22层,它就可以正常工作。

如您尚未指出“源”文件夹是否为驱动器的根目录(假设您需要的最终名称仅包含“源”及其以下文件夹),它使用pushdxcopy检索所需文件的相对路径。 ,在反斜杠上拆分检索到的列表,并将各部分连接到最终文件名中。

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "source=d:\temp\k"
    set "target=c:\somewhere"

    pushd "%source%"
    for /d %%w in ("."
    ) do for /f "tokens=1,* delims=:" %%x in ('xcopy /l /s "*.txt" "%temp%"'
    ) do for /f "tokens=1-22 delims=\" %%a in ("%%~y"
    ) do echo copy /y "%source%\%%~y" "%target%\%%~nxw%%a%%b%%c%%d%%e%%f%%g%%h%%i%%j%%k%%l%%m%%n%%o%%p%%q%%r%%s%%t%%u%%v"
    popd

该脚本仅将所需的copy命令回显到控制台。 如果输出正确,请删除echo命令。

我将使用DIR / S / B探索目录及其子文件夹,并获得易于使用的结果:

@echo off
setlocal ENABLEDELAYEDEXPANSION

set "DEST=.\output"

REM Get complete absolute path for every interesting file
for /f %%a in ('dir /S /B .\Parent\*txt') do (
    REM Process name as desired
    set "newName=%%a"
    set "newName=!newName:\=_!"
    set "newName=!newName:*Parent_=!"

    copy %%a %DEST%\!newName!
)

该脚本应该很健壮-它使用一个名为repl.bat的帮助程序批处理文件-从以下网址下载: https : repl.bat

repl.bat放在与批处理文件相同的文件夹中或路径上的文件夹中。

d:\\\\target更改为所需的文件夹-必需使用双\\
也更改\\parent

该脚本将创建一个名为temp.bat.txt的批处理文件以复制到该文件,您可以在使用记事本之前在记事本中对其进行检查。

@echo off
dir /b /s /a-d "\parent\*.ext.out" |repl "..(.*)\\(.*)\\.*\.(.*\..*)" "copy \q$&\q \qd:\\target\\$2.$3\q" x >temp.bat.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM