使用Windows批处理脚本重命名目录中的所有文件

Bla*_*ner 14 windows cmd rename batch-file

如何编写将重命名目录中所有文件的批处理文件或cmd文件?我正在使用Windows.

改变这个:

750_MOT_Forgiving_120x90.jpg
751_MOT_Persecution_1_120x90.jpg
752_MOT_Persecution_2_120x90.jpg
753_MOT_Hatred_120x90.jpg
754_MOT_Suffering_120x90.jpg
755_MOT_Freedom_of_Religion_120x90.jpg
756_MOT_Layla_Testimony_1_120x90.jpg
757_MOT_Layla_Testimony_2_120x90.jpg
Run Code Online (Sandbox Code Playgroud)

对此:

750_MOT_Forgiving_67x100.jpg
751_MOT_Persecution_1_67x100.jpg
752_MOT_Persecution_2_67x100.jpg
753_MOT_Hatred_67x100.jpg
754_MOT_Suffering_67x100.jpg
755_MOT_Freedom_of_Religion_67x100.jpg
756_MOT_Layla_Testimony_1_67x100.jpg
757_MOT_Layla_Testimony_2_67x100.jpg
Run Code Online (Sandbox Code Playgroud)

dbe*_*ham 24

一个FOR语句循环遍历名称(FOR /?帮助类型),字符串搜索和替换(键入SET /?以获取帮助).

@echo off
setlocal enableDelayedExpansion
for %%F in (*120x90.jpg) do (
  set "name=%%F"
  ren "!name!" "!name:120x90=67x100!"
)
Run Code Online (Sandbox Code Playgroud)


更新 - 2012-11-07

我已经研究了RENAME命令如何处理通配符:Windows RENAME命令如何解释通配符?

事实证明,使用RENAME命令可以非常轻松地解决此特定问题,而无需任何批处理脚本.

ren *_120x90.jpg *_67x100.*
Run Code Online (Sandbox Code Playgroud)

之后的字符数_没关系.如果120x90成为x或,重命名仍然可以正常工作xxxxxxxxxx.这个问题的重要方面是最后一个_和之间的整个文本.被替换.

  • 我不确定这是否是一个完整的例子.但是[这个](http://stackoverflow.com/a/3811991)对我来说就像一个魅力:) (3认同)
  • @Anand - 我只使用REN命令添加了一个更简单的解决方案.评论中的链接与我原来的答案基本相同. (2认同)

Iai*_*der 8

从Windows 7开始,您可以在一行PowerShell中执行此操作.

powershell -C "gci | % {rni $_.Name ($_.Name -replace '120x90', '67x100')}"
Run Code Online (Sandbox Code Playgroud)

说明

powershell -C "..."启动PowerShell会话以运行带引号的命令.命令完成后,它返回到外壳.-C是的缩写-Command.

gci返回当前目录中的所有文件.它是别名Get-ChildItem.

| % {...}制作一个管道来处理每个文件.%是别名Foreach-Object.

$_.Name 是管道中当前文件的名称.

($_.Name -replace '120x90', '67x100')使用-replace运算符创建新文件名.第一个子字符串的每次出现都被第二个子字符串替换.

rni更改每个文件的名称.第一个参数(被调用-Path)标识文件.第二个参数(被调用-NewName)指定新名称.rniRename-Item的别名.

$ dir
 Volume in drive C has no label.
 Volume Serial Number is A817-E7CA

 Directory of C:\fakedir\test

11/09/2013  16:57    <DIR>          .
11/09/2013  16:57    <DIR>          ..
11/09/2013  16:56                 0 750_MOT_Forgiving_120x90.jpg
11/09/2013  16:57                 0 751_MOT_Persecution_1_120x90.jpg
11/09/2013  16:57                 0 752_MOT_Persecution_2_120x90.jpg
               3 File(s)              0 bytes
               2 Dir(s)  243,816,271,872 bytes free

$ powershell -C "gci | % {rni $_.Name ($_.Name -replace '120x90', '67x100')}"

$ dir
 Volume in drive C has no label.
 Volume Serial Number is A817-E7CA

 Directory of C:\fakedir\test

11/09/2013  16:57    <DIR>          .
11/09/2013  16:57    <DIR>          ..
11/09/2013  16:56                 0 750_MOT_Forgiving_67x100.jpg
11/09/2013  16:57                 0 751_MOT_Persecution_1_67x100.jpg
11/09/2013  16:57                 0 752_MOT_Persecution_2_67x100.jpg
               3 File(s)              0 bytes
               2 Dir(s)  243,816,271,872 bytes free
Run Code Online (Sandbox Code Playgroud)