将文件移动到正确的文件夹并使用批处理脚本重命名它们

问题描述 投票:0回答:1

为了简化日常工作,我制作了一个批处理脚本 (.bat),它在当前文件夹中提供了 4 个子文件夹和 16 个 *.dds 文件。

这些子文件夹和文件的名称按顺序排列,例如: 文件夹名称:002360、002361、002362、002363。 文件名:file-0.dds、file-1.dds、file-2.dds、...、file-15.dds。

我想扩展这个脚本以获得以下内容:

a) 它将前 4 个文件(从“file-0.dds”到“file-3.dds”)移动到第一个文件夹(“002360”),并将它们重命名为“003760.dds” “003763.dds”。

b)接下来的 4 个文件(从“file-4.dds”到“file-7.dds”)将它们移动到下一个文件夹(“002361”)并将它们重命名为相同的名称,即“003760” .dds”到“003763.dds”。

...

d)它将最后 4 个文件(从“file-12.dds”到“file-15.dds”)将它们移动到最后一个文件夹(“002363”)并将它们重命名为相同的名称,即从“003760” .dds”到“003763.dds”。

每个文件夹移动文件的数量是相同的,我将此数字分配为变量:

%y%
第一个文件名(即“003760.dds”)可以与其他变量一起在开头输入。

我还担心文件名中的前导零。对于创建文件夹,我使用如下循环:

set /p n=Enter the number of the first zeroes in folder names:
set /p x_=Enter the name (without first zeroes) of the first folder:
set /a x=x_
set /p y_=Enter the number of folders:
set /a y=y_
set /a z=x+y-1

if %n%==2 (
    for /l %%i in (%x%, 1, %z%) do md "00%%i"
) else if %n%==3 (for /l %%i in (%x%, 1, %z%) do md "000%%i"
)

我不知道如何循环选择前几个文件并将它们移动到第一个文件夹。重命名操作可以推迟,因为可以在所有文件移动之后再进行。也许有一些我需要的命令的示例。

batch-file batch-rename file-move
1个回答
0
投票
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the directories and filenames are names
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files\t w o"
SET "destdir=u:\your results"
SET /a directorydigits=6
SET /a filedigits=6


SET /p filecount="How many files AT a time? "
SET /p dirnum="Starting directory number (omit leading zeroes)? "
SET /p rennum="Starting destination file number (omit leading zeroes)? "

SET /a dirnum+=1000000000
SET /a rennum=1000000000 + rennum
SET /a rennummax=rennum + filecount

:: This should rename "file-0..9999" to "file-00000..099999"
for /L %%e in (0,1,9999) do IF EXIST "%sourcedir%\file-%%e.dds" (
 SET /a filenumber=1000000000 + %%e
 ren "%sourcedir%\file-%%e.dds" "file-!filenumber:~-5!.dds"
 ) ELSE GOTO continue

:continue

FOR /f "delims=" %%e IN ('dir /b /a-d "%sourcedir%\file-*.dds"') DO (
 SET "destsubdir=%destdir%\!dirnum:~-%directorydigits%!"
 ECHO MD "!destsubdir!" 2>NUL
 ECHO MOVE "%sourcedir%\%%e" "!destsubdir!\!rennum:~-%filedigits%!.dds"
 SET /a rennum+=1
 IF !rennum! geq !rennummax! SET /a rennum-=filecount&SET /a dirnum+=1
)

GOTO :EOF

在应用于真实数据之前,始终验证测试目录。

如果使用有意义的变量名,事情会变得容易得多。

所需的 MD 命令仅用于测试目的。

验证命令正确后
,将 ECHO 更改为
ECHO MD
以实际创建目录。我已附加
MD
来抑制错误消息(例如,当目录已存在时)
所需的 MOVE 命令仅用于测试目的。 

确认命令正确后

,将

2>nul
更改为 ECHO 以实际移动文件。附加
ECHO MOVE
以抑制报告消息(例如
MOVE
>nul
命令仅生成

1 file moved

处理的文件名列表(/b = 基本,/a-d = 无目录名)。

数学运算应该是显而易见的。要了解 
dir
的情况,请尝试 Stephan 的 DELAYEDEXPANSION 链接:
https://stackoverflow.com/a/30284028/2128947


© www.soinside.com 2019 - 2024. All rights reserved.