30

我已经看过一些关于 SO 的脚本示例,但它们似乎都没有提供如何从 .t​​xt 列表中读取文件名的示例。

这个例子很好,这样就可以将A文件夹中的所有文件复制到B文件夹中

xcopy c:\olddir\*.java c:\newdir /D /E /Q /Y

但我需要类似下一个的东西,我可以在其中填充源文件夹和目标文件夹:

 @echo off
 set src_folder = c:\whatever\*.*
 set dst_folder = c:\foo
 xcopy /S/E/U %src_folder% %dst_folder%

而不是src_folder = c:\whatever\*.*,那些*.*需要是从 txt 文件中读取的文件列表。

文件列表.txt(示例)

file1.pds
filex.pbd
blah1.xls

有人可以建议我怎么做吗?

4

6 回答 6

50

给定名为 的文件中的文件名列表File-list.txt,以下行应该可以满足您的要求:

@echo off
set src_folder=c:\whatever
set dst_folder=c:\target
for /f "tokens=*" %%i in (File-list.txt) DO (
    xcopy /S/E "%src_folder%\%%i" "%dst_folder%"
)
于 2011-06-06T21:24:48.573 回答
20

我只是尝试使用 Frank Bollack 和 sparrowt 的答案,但没有成功,因为它包含 xcopy 的 /U 开关。我的理解是 /U 意味着文件只有在目的地已经存在时才会被复制,这对我来说不是这样,对于原始提问者来说似乎也不是这样。它可能意味着是 /V 用于验证,这会更有意义。

删除 /U 开关解决了这个问题。

@echo off
set src_folder=c:\whatever
set dst_folder=c:\target
for /f "tokens=*" %%i in (File-list.txt) DO (
xcopy /S/E "%src_folder%\%%i" "%dst_folder%"
)
于 2015-06-26T05:34:26.227 回答
3

这将做到:

@echo off
set src_folder=c:\batch
set dst_folder=c:\batch\destination
set file_list=c:\batch\file_list.txt

if not exist "%dst_folder%" mkdir "%dst_folder%"

for /f "delims=" %%f in (%file_list%) do (
    xcopy "%src_folder%\%%f" "%dst_folder%\"
)
于 2011-06-06T21:24:38.493 回答
3

以下将从列表中复制文件并保留目录结构。例如,当您需要压缩在一系列 Git/SVN 提交中更改的文件时很有用¹。它还将处理目录/文件名中的空格,并适用于相对路径和绝对路径:

(基于这个问题:How to expand two local variables inside a for loop in a batch file

@echo off

setlocal enabledelayedexpansion

set "source=input dir"
set "target=output dir"

for /f "tokens=* usebackq" %%A in ("file_list.txt") do (
    set "FILE=%%A"
    set "dest_file_full=%target%\!FILE:%source%=!"
    set "dest_file_filename=%%~nxA"
    call set "dest_file_dir=%%dest_file_full:!dest_file_filename!=%%"
    if not exist "!dest_file_dir!" (
        md "!dest_file_dir!"
    )
    set "source_file_full=%source%\!FILE:%source%=!"
    copy "!source_file_full!" "!dest_file_dir!"
)
pause

请注意,如果您的文件列表具有绝对路径,则您也必须设置source为绝对路径。


[¹] 如果使用 Git,请参阅:Export only modified and added files with folder structure in Git

于 2016-12-13T13:41:38.037 回答
1

这也将保留文件的原始文件目录:

@echo off
set src_folder=c:\whatever
set dst_folder=c:\target
set file_list=C:\file_list.txt

for /f "tokens=*" %%i in (%file_list%) DO (
   echo f | xcopy /E /C /R /Y "%src_folder%\%%i" "%dst_folder%\%%i"
)
于 2016-12-09T11:18:21.980 回答
0

也可以使用robocopy和 Not use for loop with xcopy - 可以解析参数中的文件列表。

robocopy Source_folder Destination_folder [files_to_copy] [options]

用空格分隔符复制它的字符串的文件。例如:

robocopy . "d:\my folder" *.txt "my file one.cpp" file2.cpp
robocopy "d:\F 15" "d:\backup\F 15" /E
于 2021-07-28T16:47:33.770 回答