如何基于文件名的第一部分和第二部分创建文件夹并将文件移动到该文件夹​​中? [英] How to create folder based on first and second part of file name and move files into the folder?

查看:101
本文介绍了如何基于文件名的第一部分和第二部分创建文件夹并将文件移动到该文件夹​​中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下批处理脚本,以根据今天的日期创建一个文件夹,然后根据文件名将文件分组到文件夹中.

I created the following batch script to create a folder based on today's date and then group files into folders based on the file name.

例如文件

JIM_BRICKMAN_QPS.avi
JIM_BRICKMAN_Slice.avi
JIM_BRICKMAN_Slice.jpg

被移动到文件夹BRICKMAN.

这很好,但是,尝试修改批处理文件以将新创建​​的文件夹移动到新创建的日期文件夹中时失败,或者在遍历循环时覆盖了这些文件夹.

This works fine, however, attempts to modify the batch file to move the newly created folders into the newly created date folder fail or overwrite the folders when going through the loop.

for /F "tokens=1-4 delims=/" %%A in ('date /t') do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
if not exist "%CurrentDate%" md %CurrentDate%

for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,* delims=_" %%D in ("%%~nA") do (
        md "%%D" 2>nul
        echo Moving file %%A to folder %%D
        move "%%A" "%%D" >nul
    )
)

echo Finished

此外,我似乎无法获得令牌来忽略第一个定界符,因此该文件夹的标题为JIM_BRICKMAN而不只是BRICKMAN.

Additionally, I can't seem to get the token to ignore the first delimiter so that the folder is titled JIM_BRICKMAN and not just BRICKMAN.

我在评论中的建议之后重写了批处理文件:

I rewrote the batch file after the suggestions in the comments:

set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
if not exist "%CurrentDate%" md %CurrentDate%
for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
        md "%%D_%%E" 2>nul
        move "%%A" "%%D_%%E" >nul
    )
)

但是脚本似乎炸毁了.我尝试捕获该错误,但是尽管我在脚本中放入了 PAUSE ,它仍然关闭了.

But the script seems to bomb out. I tried to capture the error, but it closes despite me putting PAUSE in the script.

推荐答案

双击开发中的批处理文件不是一个好主意,因为这会导致启动

Double clicking on a batch file in development is no good idea because this results in starting

%SystemRoot%\System32\cmd.exe /c "batch file name with full path and extension"

由于可以在命令提示符窗口中运行cmd /?时读取它,因此选项/C表示在执行命令,可执行文件或脚本后立即关闭命令进程及其控制台窗口独立于结束执行的原因而完成.

As it can be read on running cmd /? from within a command prompt window, the option /C means close the command process and its console window immediately after execution of command, executable or script finished independent on the reason for ending the execution.

要在开发中调试批处理文件,最好要

For debugging a batch file in development it is much better to

  1. 打开命令提示符窗口,
  2. 使用命令 CD 将当前目录更改为批处理文件的目录,然后
  3. 通过键入批处理文件的名称并按 RETURN ENTER 键来运行该批处理文件.
  1. open a command prompt window,
  2. change the current directory with command CD to directory of batch file and
  3. run the batch file by typing its name and hitting key RETURN or ENTER.

对于应该独立于当前目录所在目录的批处理文件,建议忽略第2点,然后输入完整路径运行批处理文件,文件名和文件扩展名用双引号括起来,而不是当前目录批处理文件的目录.

For batch files which should work independent on which directory is the current directory, it is advisable to omit point 2 and run the batch file with entering its full path, file name and file extension enclosed in double quotes with current directory being not the directory of the batch file.

批处理文件是在命令提示符窗口中使用以下命令执行的:

A batch file is executed from within a command prompt window with:

%SystemRoot%\System32\cmd.exe /K BatchFileNameAsTyped

选项/K表示保持命令进程正在运行,这将导致在执行命令/可执行文件/脚本后也保持打开命令提示符窗口的状态,从而可以读取错误消息.

The option /K means keep command process running which results in keeping also command prompt window opened after execution of command/executable/script which makes it possible to read error messages.

在命令提示符窗口中输入向上箭头向下箭头后,可以使用它们重新加载命令行,从而在重新创建命令行后轻松地再次运行批处理文件在GUI文本编辑器中进行修改.

The keys UP ARROW and DOWN ARROW can be used to reload command lines once entered in command prompt window making it easy to run the batch file once again after making a modification in GUI text editor.

并且从批处理文件的第一行中删除了@echo off,或者更改为@echo ON,或者在开始时使用命令 REM ::(无效标签)对此行进行了注释,还可以查看在应用立即环境变量扩展后Windows命令解释程序真正执行了哪些行,以及在语法错误的情况下发生错误的地方.

And with having @echo off removed from first line of batch file, or changed to @echo ON, or commented out this line with command REM or with :: (invalid label) at beginning, it is also possible to see which lines Windows command interpreter really executes after applying immediate environment variable expansion and where an error occurs in case of a syntax error.

第二批代码的错误所在行:

Wrong on second batch code is the line:

for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (

指定为循环变量必须始终为1个字符.正确的是:

Specified as loop variable must be always 1 character. Right would be:

for /f "tokens=1,2 delims=_" %%D in ("%%~nA") do (


命令echo %DATE%使用我的帐户和今天的区域设置在计算机上输出日期01.04.2017.


The command echo %DATE% outputs on my computer with my account and my region settings today the date 01.04.2017.

命令echo %DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%输出01-04-2017.

因此脚本的这一部分有效.

So this part of the script works.

提示:格式为YYYY-MM-DD的目录列表要好于格式为DD-MM-YYYY的目录.默认情况下,格式为YYYY-MM-DD的目录列表将按默认字母顺序自动排序,并且此日期格式也按从最早到最新的顺序进行排序.日期格式DD-MM-YYYY导致默认情况下按字母顺序对目录进行奇怪的排序.

Hint: A list of directories in format YYYY-MM-DD is better than in format DD-MM-YYYY. The list of directories with format YYYY-MM-DD sorted alphabetically as by default is automatically with this date format also sorted from oldest to newest. Date format DD-MM-YYYY results in a weird list of the directories on being sorted alphabetically as by default.

此任务的批处理文件可能是:

A batch file for this task could be:

@echo off
set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
for %%A in (*.avi *.jpg) do (
    for /F "tokens=1,2 delims=_" %%D in ("%%~nA") do (
        if not "%%E" == "" (
            md "%CurrentDate%\%%D_%%E" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D_%%E\"
        ) else (
            md "%CurrentDate%\%%D" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D\"
        )
    )
)
set "CurrentDate="

内循环的工作方式对此任务最有趣.

How the inner loop works is most interesting for this task.

for /F"%%~nA"表示命令 FOR 应该仅处理* .avi或* .jpg文件的文件名,而外部 FOR 循环.

for /F and "%%~nA" means the command FOR should process just the file name of the *.avi or *.jpg file without file extension found by outer FOR loop.

delims=_表示 FOR 命令应使用下划线作为分隔符将字符串分成多个部分(令牌).第一个文件名为JIM_BRICKMAN_QPS,它将被拆分为:

delims=_ means the FOR command should split up the string into multiple parts (tokens) using underscore as delimiter. The first file name is JIM_BRICKMAN_QPS which would be split up to:

    FOR 命令行中指定的
  1. JIM分配给循环变量D
  2. BRICKMAN分配给循环变量E,它是 ASCII表中的下一个字符,D
  3. QPS分配给循环变量F.
  1. JIM assigned to loop variable D being specified in FOR command line,
  2. BRICKMAN assigned to loop variable E which is the next character in ASCII table after D and
  3. QPS assigned to loop variable F.

此字符串拆分功能是为什么解释循环变量区分大小写而解释环境变量不区分大小写的原因.

This string split feature is the reason why loop variables are interpreted case-sensitive while environment variables are interpreted not case-sensitive.

仅关注第一个和第二个字符串部分.因此,内部 FOR 在确定了前两个下划线定界的字符串并将它们分配给循环变量DE之后,可以停止字符串拆分.

With tokens=1,2 is specified that just first and second string parts are of interest. So inner FOR can stop string splitting after having already determined the first two underscore delimited strings and having assigned them to the loop variables D and E.

FOR 如果可以确定至少一个由下划线分隔的字符串,则执行命令块.因此,循环变量D可能具有字符串值,但是循环变量E是空字符串,例如,如果文件名不包含任何下划线.这就是 IF 条件的原因.

FOR executes the command block if it could determine at least 1 string delimited by an underscore. So it is possible that loop variable D has a string value, but loop variable E is an empty string, for example if the file name does not contain any underscore. That is the reason for the IF condition.

MD 命令创建的命令扩展名默认为整个目录树.因此,在搜索* .avi和* .jpg文件之前,无需显式创建日期子目录.这样很好,因为当当前目录中没有* .avi和* .jpg文件时,它可以避免创建空的日期目录.

The command MD creates with command extensions enabled as by default the entire directory tree. Therefore it is not necessary to create the date subdirectory explicitly before searching for *.avi and *.jpg files. That is good as it avoids creating empty date directories when there are no *.avi and *.jpg files in current directory.

由于应将当前目录中的* .avi和* .jpg文件移动到DD-MM-YYYY\Token1_Token2,因此在创建目录和移动文件时,当然还必须指定带有今天日期字符串的环境变量.

As the *.avi and *.jpg files in current directory should be moved to DD-MM-YYYY\Token1_Token2 it is of course necessary to specify also the environment variable with todays date string on creating the directory and moving the file.

通过2>nul重定向 MD 输出的错误消息(如果目录存在(或由于缺少权限而无法创建目录),以处理 STDERR ).将设备 NUL 禁止显示.

The error message output by MD if the directory exists (or when it fails to create the directory because of missing permissions) to handle STDERR is redirected with 2>nul to device NUL to suppress it.

MOVE 命令与选项/Y一起使用,即使当前文件已存在于目标文件夹中,该文件也可以移动到目标文件夹中.

The MOVE command is used with option /Y to move the file to target folder even if the current file exists already in target folder.

要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • for /?
  • if /?
  • md /?
  • move /?
  • set /?
  • echo /?
  • for /?
  • if /?
  • md /?
  • move /?
  • set /?

还请阅读有关使用命令重定向操作符的Microsoft文章.

Read also the Microsoft article about Using Command Redirection Operators.

这篇关于如何基于文件名的第一部分和第二部分创建文件夹并将文件移动到该文件夹​​中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆