繁体   English   中英

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

[英]Rename all files in a directory with a Windows batch script

如何编写将重命名目录中所有文件的批处理文件或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

对此:

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

一个FOR语句循环遍历名称(输入FOR /?表示帮助),以及字符串搜索和替换(键入SET /?表示帮助)。

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


更新 - 2012-11-07

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

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

ren *_120x90.jpg *_67x100.*

_之后的字符数无关紧要。 如果120x90变为xxxxxxxxxxx ,重命名仍然可以正常工作。 这个问题的重要方面是最后_和之间的整个文本. 被取代了。

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

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

说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM