Windows脚本FOR命令重命名目录中的所有文件

时间:2008-10-10 13:47:54

标签: windows cmd

我正在尝试使用 FOR 命令重命名Windows目录中的所有文件,如下所示:

for %1 in (*.*) do ren %1 test%1 

E.g。这会将文件 enc1.ctl 重命名为 testenc1.ctl enc2.ctl testenc2.ctl

这不是我想要的。我想要的是 enc1.ctl 重命名为 test1.ctl enc2.ctl 重命名为 test2.ctl

我该怎么做?


@Akelunuk: 谢谢,那种工作,但我有文件名称

h263_enc_random_pixels_1.ctl,h263_enc_random_pixels_2.ctl 我要重命名为

分别

test1.ctl和test2.ctl

那怎么样?

4 个答案:

答案 0 :(得分:2)

我知道了!

for %1 in (.) do ren %1 t%1

然后:

ren tenc*.* test*.*

答案 1 :(得分:1)

如果您知道文件数量(例如10),则可以使用

for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl

答案 2 :(得分:1)

我不确定它是否可以批量生产,但我再也没有掌握这种原始语言... :-P

如果CMD不是强制性的,但你不能使用一个好的文件重命名器,你可以用WSH做到这一点:

var path= "E:/tmp";

var fso = WScript.CreateObject("Scripting.FileSystemObject");
var folder = fso.GetFolder(path);
var files = new Enumerator(folder.files);
for (; !files.atEnd(); files.moveNext())
{
  var file = files.item();
  var fileName = file.Name;
  var p = /^enc(\d+)\.ctl$/.exec(fileName);
  if (p != null)
  {
    var newFileName = "test" + p[1] + ".ctl";
    // Optional feedback
    WScript.echo(fileName + " -----> " + newFileName);
    file.Move(newFileName);
  }
}

当然,把它放在file.js中 我实际上使用file.Copy(file.ParentFolder + "/SO/" + newFileName);进行了测试,以避免丢失文件...

HTH。

答案 3 :(得分:0)

这会使用PREFIX和今天的日期和时间重命名目录中所有过滤文件类型的文件

@echo ON
cls
for %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)

echo Date format = %myfiledate%
echo dd = %myfiledate:~0,2%
echo mm = %myfiledate:~3,2%
echo yyyy = %myfiledate:~6,4%
echo.
echo Time format = %myfiledate%
echo hh = %myfiledate:~11,2%
echo mm = %myfiledate:~14,2%
echo AM = %myfiledate:~17,2%
echo.
echo Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%
ECHO "TEST..." > "test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt"
PAUSE

此回声成功地将修改日期和时间作为后缀修改,但不会将信息解析为重命名。我无法弄清楚为什么,但它非常接近。也许有人不能调整以适合你的目的。

@echo ON
setlocal
cls
for %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)

:DATETIME
echo Date format = %myfiledate%
echo dd = %myfiledate:~0,2%
echo mm = %myfiledate:~3,2%
echo yyyy = %myfiledate:~6,4%

echo Time format = %myfiledate%
echo hh = %myfiledate:~11,2%
echo mm = %myfiledate:~14,2%
echo AM = %myfiledate:~17,2%
 = %myfiledate:~17,2%
echo.

echo Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%
ECHO "TEST..." > "test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt"

for /f "delims=" %%a in ('dir *.pdf /t:a /a:-d /b /s') do call :RENAME "%%a"

:RENAME
REM for /f "tokens=1-6 delims=/ " %%a in ('dir %%a /t:w^|find "/"') do (
ren %%a "3DC-test-OFF-ELE-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%~x1")
PAUSE
GOTO :EOF