【问题标题】:How to copy files into folders based on first 15 characters of file and folder name?如何根据文件和文件夹名称的前 15 个字符将文件复制到文件夹中?
【发布时间】:2016-12-23 07:36:35
【问题描述】:

我想从源文件夹中复制 1000 多个文件,例如

sourcefolder\prod_de_7290022.xlsx
sourcefolder\prod_de_1652899.xlsx
sourcefolder\prod_de_6272899.xlsx
sourcefolder\prod_de_6189020.xlsx
sourcefolder\prod_de_7290022.wav
sourcefolder\prod_de_1652899.wav
sourcefolder\prod_de_6272899.wav
sourcefolder\prod_de_6189020.wav
sourcefolder\prod_de_7290022_mark.xlsx
sourcefolder\prod_de_1652899_mark.xlsx
sourcefolder\prod_de_6272899_mark.xlsx
sourcefolder\prod_de_6189020_mark.xlsx

到正确的目标文件夹。文件夹名称 - 基于另一个例程 - 很长,只有前 15 个字符与每个文件名的前 15 个字符相同,例如:

destination\prod_de_1652899_tool_big\
destination\prod_de_6272899_bike_red\
destination\prod_de_6189020_bike-green\
destination\prod_de_7290022_camera_good\

我正在寻找将文件复制到文件夹中的例程,例如将sourcefolder\prod_de_1652899.xlsx 复制到destination\prod_de_1652899_tool_big\

这里有人对批处理/脚本有好的想法吗?

【问题讨论】:

标签: batch-file


【解决方案1】:

我建议将此注释的批处理代码用于此任务:

@echo off
setlocal EnableExtensions
set "SourceFolder=sourcefolder"
set "TargetFolder=destination"

rem Call subroutine CopyFile for each non hidden and
rem non system file found in specified source folder
rem and then exit processing of this batch file.

for %%I in ("%SourceFolder%\*") do call :CopyFile "%%~fI"

endlocal
goto :EOF


rem This is a subroutine called for each file in source folder.
rem It takes the first 15 characters from each file name passed
rem to this subroutine via first parameter and search for a
rem folder in target folder starting with same 15 characters.
rem If such a folder is found, the file is copied to this folder
rem and the subroutine is exited.
rem Otherwise a new folder is created for the file and if
rem this is indeed successful, the file is copied into the
rem newly created folder with an appropriate message.

:CopyFile
set "FileName=%~n1"
set "DirectoryName=%FileName:~0,15%"
for /D %%D in ("%TargetFolder%\%DirectoryName%*") do (
    copy /B /Y %1 /B "%%~D\" >nul
    goto :EOF
)

set "NewFolder=%TargetFolder%\%DirectoryName%_new"
md "%NewFolder%"
if exist "%NewFolder%\" (
    echo Created new folder: %NewFolder%
    copy /B /Y %1 /B "%NewFolder%\" >nul
    goto :EOF
)

echo Failed to create folder: %NewFolder%
echo Could not copy file: %1
goto :EOF

要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

  • call /?
  • copy /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • md /?
  • rem /?
  • set /?
  • setlocal /?

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 2017-03-15
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2015-07-31
    • 2021-04-10
    相关资源
    最近更新 更多