Windows 使用源文件夹作为名称,将文件从源目录树复制到新位置
我有一个文件和文件夹的目录,例如:Windows 使用源文件夹作为名称,将文件从源目录树复制到新位置,windows,batch-file,Windows,Batch File,我有一个文件和文件夹的目录,例如: \Parent |-\Child ||-\Test |||-\Content |||-targetfile.ext.out |-\AnotherChild ||-anothertargetfile.ext.out 我想将任何包含.ext.out的文件复制到另一个目录,但用目录结构重命名它 例如:targetfile.ext.out将被复制到名为“ParentChildTestContent.ext.out”的已定义目录中,“anothertargetfile
\Parent
|-\Child
||-\Test
|||-\Content
|||-targetfile.ext.out
|-\AnotherChild
||-anothertargetfile.ext.out
我想将任何包含.ext.out的文件复制到另一个目录,但用目录结构重命名它
例如:targetfile.ext.out将被复制到名为“ParentChildTestContent.ext.out”的已定义目录中,“anothertargetfile.ext.out”将被复制到与“AnotherChild.ext.out”相同的已定义目录中。为了简化脚本,可以剥离.out。我将使用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的助手批处理文件
-下载自:
将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
只要你的文件夹结构深度不超过22层,这就可以了 由于您没有指出“源”文件夹是否是驱动器的根目录,假设您需要的最终名称仅包含“源”及其以下文件夹,它使用
pushd
和xcopy
检索到所需文件的相对路径,在反斜杠上拆分检索到的列表,并将零件合并到最终文件名中
@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
命令。非常感谢。经过一些小的调整,这正是我所希望的。我将最后一行修改为使用xcopy,并在目标文件的末尾添加了一个“*”以假设文件,所有操作都很顺利。