Batch file 批处理文件:根据文件名的一部分将文件移动到文件夹,根据文件夹名的一部分将文件移动到文件夹
找到pyhton解决方案,但我需要基于批处理文件的解决方案 有许多文件:Batch file 批处理文件:根据文件名的一部分将文件移动到文件夹,根据文件夹名的一部分将文件移动到文件夹,batch-file,directory,filenames,batch-processing,move,Batch File,Directory,Filenames,Batch Processing,Move,找到pyhton解决方案,但我需要基于批处理文件的解决方案 有许多文件: SSP4325_blah-blah-blah.xml JKP7645_blah.xml YTG6457-blah-blah.xml 以及包含一段文件名的文件夹名: RefID-SSP4325,JKP7645,GHT1278,YRR0023 RefID-YTG6457 我正在寻找一个批处理解决方案,它将读取文件名前面的一部分(在第一个破折号或下划线之前),然后将该文件移动到文件夹中,其中文件名前面作为文件夹名的一部分
- SSP4325_blah-blah-blah.xml
- JKP7645_blah.xml
- YTG6457-blah-blah.xml
- RefID-SSP4325,JKP7645,GHT1278,YRR0023
- RefID-YTG6457
@ECHO OFF
SETLOCAL
设置“sourcedir=U:\sourcedir”
设置“destdir=U:\destdir”
对于/f“delims=”%%a IN(
'dir/b/a-d“%sourcedir%\*.xml”'
)做(
对于(“%%a”)中的/f“令牌=1delims=-”%%b(
对于/f“delims=”%%d IN(
'dir/b/ad”%destdir%\*%%b*“'
)做(
回显(移动“%%a”“%destdir%%\%%d\”
)
)
)
后藤:EOF
您需要更改sourcedir
和destdir
的设置以适应您的环境
所需的移动命令仅用于测试。ECHO
在验证命令正确后,更改ECHO(MOVE
至MOVE
以实际移动文件。追加>nul
以抑制报告消息(例如1个文件已移动
)
建立目录后,外部循环将文件名放入%%a
,下一个循环获取该名称的第一部分,直到但不包括第一个-
或
(指定的delims
)放入%%b
内部循环在目标目录中找到包含
%%b
的目标目录,并构造相应的move
行。此解决方案只需查看文件夹一次并将其存储在数组中,因此此方法应能运行得更快
@echo off
setlocal EnableDelayedExpansion
rem Process the folders
set i=0
for /D %%a in (*) do (
rem Store this folder in the next array element
set /A i+=1
set "folder[!i!]=%%a"
rem Separate folder in parts and store the number of the array element in each one
for %%b in (%%a) do set "part[%%b]=!i!"
)
rem Process the files
for %%a in (*.xml) do (
rem Get the first part of name
for /F "delims=-_" %%b in ("%%a") do (
rem If such a folder exists...
if defined part[%%b] (
rem Get the number of the corresponding array element and move the file
for %%n in (!part[%%b]!) do ECHO move "%%a" "!folder[%%n]!"
) else (
echo No folder exists for this file: "%%a"
)
)
)
这种方法还有几个优点:您可以检查某个文件夹是否不存在,或者获取移动到每个文件夹的文件数,等等。如果您对这些点不感兴趣,只需删除if
命令并简化代码即可
有关批处理文件中的阵列管理的说明,请参见