使用批处理文件一次更改文件扩展名和名称 [英] Change file extensions and name at once using batch file

查看:165
本文介绍了使用批处理文件一次更改文件扩展名和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录,里面充满了某些软件输出的文件,如下所示:

I have a directory full of files output from some software as below:

  • 待审核001
  • 待审核002
  • 待审核003

我想使用.bat重命名它们,如下所示:

I would like to use a .bat to rename them as below:

  • Pending001.csv
  • Pending002.csv
  • Pending003.csv

有什么建议吗?

推荐答案

您可以在循环中重命名文件,使用循环变量上的修饰符~n~x分别提取名称和扩展名每个文件的名称,以新名称将它们串联起来.由于扩展名将与前导.一起提取,因此您还需要一个变量来临时存储扩展名,然后再删除..

You could rename your files in a loop, using the modifiers ~n and ~x on the loop variable to extract, respectively, the name and the extension of each file to concatenate them in the new name. As the extension would be extracted together with the leading ., you would also need a variable to temporarily store the extension before removing the ..

下面是如何实现上述示例:

Here's an example of how the above could be implemented:

@ECHO OFF
FOR %%I IN (Pending.*) DO (
  SET "ext=%%~xI"
  SETLOCAL EnableDelayedExpansion
  RENAME "%%I" "%%~nI!ext:~1!.csv"
  ENDLOCAL
)

启用延迟扩展是因为评估ext需要它.使用%的普通"扩展在这里不起作用,因为那样的话,在变量仍为空时,变量将在循环开始之前被扩展一次.相反,使用延迟扩展,该变量将在每次执行包含该变量的特定命令时(即也在循环的每次迭代中)扩展.

The delayed expansion is enabled because it is needed for the evaluation of ext. "Normal" expansion, which uses %, wouldn't work here because that way the variable would be expanded just once before the loop started, when the variable was still empty. In contrast, with the delayed expansion, the variable will be expanded every time the particular command containing it is executed, i.e. on every iteration of the loop too.

上述批处理文件将处理 current 目录中的文件,即您首先需要切换到需要处理文件的目录,然后调用该批处理.或者,如果您要在例如Windows资源管理器,您可能需要将该批次复制到包含要处理的文件的目录中,然后从那里进行调用.

The above batch file would process files in the current directory, i.e. you would first need to change to the directory where the files need to be processed, then call the batch. Or, if you would be doing that in e.g. Windows Explorer, you would likely need to copy that batch to the directory with the files to process and call it from there.

不过,或者,您可能希望使用指定要处理目录的参数来调用它.要使用该参数,请更改脚本,如下所示:

Alternatively, though, you might want to call it with a parameter specifying the directory to process. To use the parameter, change the script like this:

@ECHO OFF
FOR %%I IN ("%~1\Pending.*") DO (
  SET "ext=%%~xI"
  SETLOCAL EnableDelayedExpansion
  RENAME "%%I" "%%~nI!ext:~1!.csv"
  ENDLOCAL
)

当然,如果文件始终位于同一目录中,则还可以为其指定固定路径:

Of course, you could also just specify a fixed path to the files if they are always in the same directory:

@ECHO OFF
FOR %%I IN ("D:\path\to\files\Pending.*") DO (
  SET "ext=%%~xI"
  SETLOCAL EnableDelayedExpansion
  RENAME "%%I" "%%~nI!ext:~1!.csv"
  ENDLOCAL
)

这样,无论存储在哪里,您都可以调用该批处理.

That way you would be able to call the batch from wherever you stored it.

这篇关于使用批处理文件一次更改文件扩展名和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆