创建.BAT文件以使用输入重命名当前目录中的文件

时间:2016-01-07 06:50:58

标签: batch-file command

我正在尝试编写一个小的.bat脚本(具有有限的编程知识),允许用户输入当前版本号(例如01)和新版本号(例如02)的值,然后在里面使用这两个数字重命名命令。

echo off
cls
TITLE Version Updater
echo Use this script to update file names. This works similar to find and replace in other programs.
echo[
echo Enter the current version number (01 for example)
echo off
set /p current="Current Version: "
echo[
echo Enter the new version number (01 becomes 02 etc.)
echo off
set /p new="New Version: "
echo[
echo You will be updating all occurences of "%current%" in your file names to "%new%", if this is correct then continue, if not close this window.
pause
cd %CD%
rename *%current%* *%new%*
pause

我认为代码几乎是正确的,我只是让它引用它运行的当前目录时遇到麻烦。我将这个脚本用于计算机技能有限的人,而且我不是网络管理员,所以我不能真正做任何深入的事情。

如果有人可以帮我调整一下,那就太棒了。

干杯,

编辑1 - 评论回复 例如,test_01.tab更改为test_02.tab。它基本上将替换文件名的所有_01部分并将它们更改为_02。在这种情况下,current = 01和new = 02.虽然文件名都是不同的,所以你可能需要更改test_01.bat,testing_01.bat,所以只需将01重命名为02就是我认为它可以工作的方式。

编辑2 - 当前代码 这要归功于下面的Stephan,我认为唯一需要正确工作的是从REN命令的第二部分删除文件路径,以便它只有文件和扩展名,它应该可以工作。

@pushd %~dp0
@Echo off
CLS
setlocal enabledelayedexpansion
set /p current="Current Version: "
set /p new="New Version: "

for /R %%a in (*_%current%*) do (
  set "Name=%%~a"
  ren "%%~a" "!Name:_%current%=_%new%!"
)
pause

编辑3 - 最终代码(工作,耶!)

@pushd %~dp0
@echo off
cls
TITLE CEF File Version Updater
echo This script will update CEF file versions for TLS rejections (E.G. 4XXX_XX_1 to 4XXX_XX_2). Backup files prior to running this script as a safety measure.
echo[
echo Enter the current version number (no underscore)
echo off
set /p current="Current Version: "
echo[
echo Enter the new version number (no underscore)
echo off
set /p new="New Version: "
echo[
echo You will be updating all occurences of "_%current%" in your file names to "_%new%", is this correct?

SET /P ANSWER=Do you want to continue (Y/N)? 
if /i {%ANSWER%}=={y} (goto :yes) 
if /i {%ANSWER%}=={yes} (goto :yes) 
goto :no 
:yes 

rename *_%current%.* *_%new%.*
CLS
echo Renaming is complete, please check the new file names are correct.
pause 
exit /b 0 

:no  
exit /b 1

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

@Echo off
set /p current="Current Version: "
set /p new="New Version: "

for /R "c:\your location" %%a in (*_%current%.*) do (
ren *_%current%.* *_%new%.*
)
pause

下面是在几个测试文件上运行脚本之前和之后。

enter image description here enter image description here

答案 1 :(得分:1)

@Echo off
setlocal enabledelayedexpansion
set /p current="Current Version: "
set /p new="New Version: "

for /R %%a in (*_%current%.*) do (
  set "Name=%%~nxa"
  ECHO ren "%%~a" "!Name:_%current%=_%new%!"
)
pause

(删除ECHO,如果输出满足您的要求)