如何在将文件夹名称添加到目标文件名称的情况下复制文件? [英] How do I copy files with adding folder name to destination file name?

查看:61
本文介绍了如何在将文件夹名称添加到目标文件名称的情况下复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历子文件夹列表,以将所有文件从这些子文件夹复制到新文件夹中.我想用子文件夹名称+ - +文件名来命名目标文件夹中的复制文件,因为多个子文件夹可能包含相同名称的文件.

I need to loop through a list of sub folders to copy all files from those sub folders into new folder. I would like to have named the copied files in destination folder with sub folder name + - + file name because multiple sub folders could contain files with same name.

例如,我有以下文件:

C:\Old\Folder1\a.txt
C:\Old\Folder1\b.txt
C:\Old\Folder2\a.txt
C:\Old\Folder2\b.txt

我想将以上文件复制到新文件夹 C:\ New .最终结果应该是:

I would like to copy the above files to new folder C:\New. The final result should be:

C:\New\Folder1-a.txt
C:\New\Folder1-b.txt
C:\New\Folder2-a.txt
C:\New\Folder2-b.txt

我尝试了以下代码,但无法正常工作.

I tried the following code, but it is not working as expected.

for /r "C:\Old" %%d in (*) do copy "%%d" "C:\New\%%~nxI-%%~nxf"

如何复制将文件夹名称添加到目标文件名称的文件?

How to copy files with adding folder name to destination file name?

推荐答案

由于您的源目录中具有一定的层次结构深度,因此我建议不要使用

Since you have got a certain hierarchy depth in your source directory let me recommend not to use for /R, but for /D to enumerate directories and for to enumerate files:

@echo off
rem // Iterate through the immediate sub-directories of the source directory:
for /D %%D in ("C:\Old\*") do (
    rem // Iterate through all files in the currently iterated sub-directory:
    for %%F in ("%%~D\*.*") do (
        rem /* Copy the currently iterated file into the destination directory
        rem    and rename it so that the parent directory name is prefixed: */
        copy /-Y "%%~F" "C:\New\%%~nxD-%%~nxF"
    )
)

如果不希望提示您覆盖目标目录中已经存在的文件,请

/Y 替换/-Y .

Replace /-Y by /Y if you not want to be prompted to overwrite already existing files in the destination directory.

这篇关于如何在将文件夹名称添加到目标文件名称的情况下复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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