批处理:如何批量重命名文件(越来越近)?

时间:2012-01-23 10:35:57

标签: file-rename batch-file bulk-operations

我见过人们在Perl中这样做,但我想知道是否有办法通过批处理来做到这一点?它内置于Windows中,因此我认为知道如何使用批处理脚本更有用。它不需要在计算机上安装任何东西。

示例输入名称:myFile_55 示例输出模式:将myFile更改为picture并将数字减少13。 示例输出:picture_42

你会怎么做?我知道要重命名的批处理命令:

ren myFile_55 picture_42

所以,如果我有一个名为renamer.bat的文件,我可以添加以下内容:

for /r %%x in (%1) do ren "%%x" %2

然后我可以输入这个命令:

renamer.bat myfile* picture*

我不知道如何减少数字。

1 个答案:

答案 0 :(得分:0)

您可以将原始文件名放在for循环中,然后提取名称和数字,对数字进行数学运算,然后使用新名称和数字重新插入。只要文件名格式为name_number,您就可以使用:

REM Allow for numbers to be iterated within the for-loop i.e. the i - z
SETLOCAL ENABLEDELAYEDEXPANSION
SET i=0
SET z=13
SET newName=picture
SET workDir=C:\Path\To\Files

REM Given that filenames are in the format of 'Name_number', we're going to extract 'number
REM and set it to the i variables, then subtract it by 13, then rename the original file
REM to what the newName_x which if the filename was oldName_23 it would now be newName_10
FOR /r %%X in (%1) do (
  FOR /F "tokens=1-2 delims=_" %%A IN ("%%X") DO (
    SET i=%%B
    SET /A x=!i! - %z%

    REM ~dpX refers to the drive and path of the file
    REN "%%~dpX\%%A_%%B" "%newName%_!x!"
  )
)

编辑:编辑REN命令以包含原始文件的驱动器和路径。从小写x改为大写X,以免混淆%%~dpX