根据文件组创建文件夹

时间:2013-11-22 06:56:36

标签: batch-file

我有不同名字的文件......

Tim-01.jpg
Tim-02.jpg
Tim-03.jpg
jack-01.jpg
jack-02.jpg
jack-03.jpg etc in a single folder

我想将所有tim文件移动到Tim文件夹和jack文件到Jack文件夹等。

可以使用.bat文件吗?如果是,请分享代码。

谢谢。

3 个答案:

答案 0 :(得分:1)

@echo off
setlocal
set sourcedir=c:\sourcedir
for /f "tokens=1*delims=-" %%a in ('dir /b /a-d "%sourcedir%\*-*.*") do (
 md "%sourcedir%\%%a" 2>nul
 echo move "%sourcedir\%%a-%%b" "%sourcedir%\%%a\"
)

请注意,2>nul会抑制尝试重新创建现有目录时创建的错误消息

MOVE仅仅是ECHO。删除ECHO关键字以激活move。将>nul附加到MOVE语句以抑制“1个文件移动”消息也可能是谨慎的。

答案 1 :(得分:1)

您可能知道,Batch中没有数组。所以我们只使用一个。

@ECHO OFF &SETLOCAL
for /f "tokens=1*delims=-" %%a in ('dir /b /a-d *-*.jpg') do set "$%%a=%%a"
for /f "tokens=1*delims==" %%a in ('set $') do robocopy "%cd%" "%cd%\%%b" "%%b*" /mov /l

/l移除robocopy以使其正常运行。

答案 2 :(得分:0)

编辑 - 更改了代码以减少文件移动次数。现在,所有具有相同前缀的文件都会在一个命令中移动。

@echo off

    setlocal enableextensions

    rem source of images
    set "_dir=."

    rem for each jpg with a dash in its name
    for %%f in ("%_dir%\*-*.jpg") do (

        rem if the file still exists (maybe it has been moved) 
        rem then split the file name with the dash as delimiter
        if exist "%%~ff" for /F "tokens=1 delims=-" %%s in ("%%~nf") do (

            rem and if we get a folder target, move the all the files 
            rem with same prefix to proper folder
            if not "%%~s"=="" (
                robocopy "%_dir%" "%_dir%\%%~s" "%%~s-*.jpg" /mov /njs /njh
            )
        )
    )

    endlocal

EDIT2 - 已更改以适应评论

@echo off

    setlocal enableextensions enabledelayedexpansion

    rem source of images
    set "_dir=."

    rem for each jpg with a dash in its name
    for %%f in ("%_dir%\*-??.jpg") do (

        rem if the file still exists (maybe it has been moved) 
        if exist "%%~ff" (

            rem get the filename without the 3 last characters
            set "_target=%%~nf"
            set "_target=!_target:~0,-3!"

            rem and if we get a folder target, move the all the files 
            rem with same prefix to proper folder
            if not "!_target!"=="" (
                robocopy "%_dir%" "%_dir%\!_target!" "!_target!-??.jpg" /mov /njs /njh
            )
        )
    )

    endlocal