首页 > 解决方案 > 根据部分文件名将文件移动到目录

问题描述

我有这样的文件名:

我需要将它们移动到基于名称中 # 之后的 4 或 5 位数字的目录。我找到了一个批处理文件,但它需要在文件名中具有相同位置的目录名和相同的长度。

@echo off &setlocal
for /f "delims=" %%i in ('dir /b /a-d *.text') do (
set "filename1=%%~i"
setlocal enabledelayedexpansion
set "folder1=!filename1:~0,1!"
mkdir "!folder1!" 2>nul
move "!filename1!" "!folder1!" >nul
endlocal
)

如何修改此批处理文件以搜索 4 或 5 位数字,而不是数字必须位于名称中的固定位置?谢谢!

标签: batch-file

解决方案


我可能会使用以下代码来实现您的目标:

rem /* Loop through (unhidden) files whose names contain the sequence ` #`;
rem    split the file names at the `#` character then (there should be only one);
rem    the part before `#` is available in `%%E`, the part after `#` in `%%F`: */
for /F "tokens=1* eol=# delims=#" %%E in ('dir /B /A:-D-H-S "* #*.msg"') do (
    rem // Split off the first space-separated word from the second name part:
    for /F "eol= " %%G in ("%%~nF") do (
        rem /* Use that word as the name of a sub-directory and create it
        rem    (` 2> nul` suppresses error messages when it already exists): */
        md "%%G" 2> nul
        rem /* Actually move the currently iterated file into the sub-directory
        rem    (there will appear a prompt when the target file already exists;
        rem     to avoid that, use the `/Y` option of `move` to force overwriting,
        rem     or put `if not exist "%%G\%%E#%%F" ` in front of `move` to avoid
        rem     overwriting; append ` > nul` to suppress text `1 file(s) moved.`): */
        move "%%E#%%F" "%%G\"
    )
)

推荐阅读