我只是想知道我是否使用How to copy files into folders based on first 15 characters of file and folder name?上的答案中张贴的代码正确修改了源位置和目标位置
我无法让它运行。我只是想创建一个名为前9个字符的文件夹,并将所有匹配前9个字符的文件移动到该文件夹中。
@echo off
setlocal EnableExtensions
set "SourceFolder=C:\PRASINUS\July #2"
set "TargetFolder=C:\PRASINUS\Test 1"
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 9 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 9 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,9%"
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
答案 0 :(得分:3)
代码格式化:剪切并粘贴代码;选择它并按编辑框上方栏中的{}
以缩进每行4个空格(表示“代码”)
您需要在\
中的%SourceFolder%
和*
之间添加"%SourceFolder%*"
,以便向cmd
表明您想要所有文件(*
)在目录%SourceFolder%
内,而不是匹配“%SourceFolder%+ anystring ”的文件
directoryname
变量设置正确(但是您是否担心短于9个字符的名称?)
然后,您似乎想检查是否存在从%directoryname%
开始的任何目录,并将找到的文件名复制到找到的第一个名称;如果找不到目录,则创建一个新目录;检查它是否已创建,并根据需要进行复制或通知。
所有这些都显示正常。但是,如果要在FAT格式的驱动器上设置目标,则应注意目录名称不一定按字母顺序返回,因此directory_old
可能会出现在directory_new
之前(如果两者都存在)。 / p>
我必须祝贺你使用过的文件数量。我倾向于使用::
代替rem
,因为我觉得它更易于阅读 - 您不会“阅读”rem
“字”,因为眼睛会忽略::
1}}因为它不是一个单词。请注意,::-comments
可能不会在代码块(带括号的系列语句)中使用
答案 1 :(得分:0)
您找到的示例脚本的替代方法,(最低要求Windows Vista):
@Echo Off
Set "SRC=C:\PRASINUS\July #2"
Set "DST=C:\PRASINUS\Test 1"
SetLocal EnableDelayedExpansion
If Not Exist "%SRC%\" (Exit/B) Else If Not Exist "%DST%\" Exit/B
For /F "Delims=" %%A In ('Where "%SRC%":?????????*.*') Do (Set "FNX=%%~nA"
If Not Exist "%DST%\!FNX:~,9!\" (MD "%DST%\!FNX:~,9!" 2>Nul
If ErrorLevel 1 Echo Unable to create directory %DST%\!FNX:~,9!)
If Exist "%DST%\!FNX:~,9!\" (Move /Y "%%A" "%DST%\!FNX:~,9!">Nul 2>&1
If ErrorLevel 1 Echo Unable to move %%A to %DST%\!FNX:~,9!))
Timeout -1
Exit/B
以上是根据要求提供的前九个字符。要更改为15个字符,请将9
的每个实例替换为15
,并将顺序?
的数量与15
相匹配。