Windows 批处理文件根据文件名将文件移动到子文件夹

Windows 批处理文件根据文件名将文件移动到子文件夹

我从未构建过批处理,而且很难找到执行以下操作的语法。我在一个目录中存储了大量文件,我希望根据以下逻辑将它们移动到子文件夹中(一些已经存在,其他待创建):

01202000088000.pdf

characters 1,2 -> first folder
characters 3,4 -> second folder
characters 5,6,7,8,9 -> third folder

我需要将01202000088000.pdf文件移动到01\2020\00088\,因此重命名01202000088000.pdf01\2020\00088\01202000088000.pdf

我非常感谢你的帮助。

编辑:感谢建议,我还创建了批处理版本:

@echo off
setlocal enabledelayedexpansion
rem For each file in your folder
for %%a in (*.pdf) do (
    echo filename=%%a
    rem check if the it is not our script
    if "%%a" NEQ "%0" (
        set foldername=%%a
        set foldername=..\!foldername:~0,2!\!foldername:~2,4!\!foldername:~6,5!\
        echo foldername=!foldername!
        rem check if forlder exists, if not it is created
        if not exist "!foldername!" mkdir "!foldername!"
        rem Move (or change to copy) the file to directory
        move "%%a" "!foldername!\"
    )
)

答案1

除非你正在做历史研究,否则没有理由去学习。 使用电源外壳

$Source = 'c:\PDF Folder'
GEt-ChildItem $Source *.pdf | ForEach{
   $Destination = ($_.Name.Substring(0,2)),($_.Name.Substring(2,4)),($_.Name.Substring(6,5)) -join '\'
   If ( -not ( Test-Path $Destination )) {
       mkdir $Destination | out-null
   }
   Move-Item $_.FullName $Destination
}

答案2

这是实现此目的的方法。我自己喜欢批处理函数(通过调用),这就是我使用它的原因。其他人喜欢使用 () 括号和延迟扩展。两者都没错。

如下所述,该函数可以被压缩成两行,但这样你就无法理解我在字符串解析方面所做的事情,所以我把它写得很冗长。

    @echo off

    :: This script assumes that all PDFs req'd are in the
    :: current directory and all have names with the format
    :: 01202000088000.pdf

    :: Get all of the PDF files in the current directory.  Pass them
    :: to a function called ParseFilenameMoveFile one at a time
    for %%f in (*.pdf) do call :ParseFilenameMoveFile "%%f"
    goto :EOF

    :: ----------------------------------------------------------------
    :: this could be folded into two lines but wouldn't be readable.
    :: ----------------------------------------------------------------
    :ParseFilenameMoveFile
    set InputFile=%~1
    set firstFolderChars=%InputFile:~0,2%
    set secondFolderChars=%InputFile:~2,4%
    set thirdFolderChars=%ParsedFilename:~6,5%

    set outputFolder=%firstFolderChars%\%secondFolderChars%\%thirdFolderChars%

    if not exist %outputFolder% mkdir %outputFolder%
    move %InputFile% %outputFolder%

    goto :EOF

答案3

如果语法相同,请尝试使用免费重命名实用程序,如 Bulk Rename Utility。然后,在 Windows 资源管理器中将它们分类到目录中可能很容易完成。

相关内容