替换文件名中的文本

时间:2018-04-20 22:36:18

标签: batch-file

我要做的是用我的计算机名替换部分文件名。

@echo off
set host=%COMPUTERNAME%
set host=%host:~4, -2%

for /f "delims=" %%a in ('dir /a:-d /o:n /b') do call :next "%%a"
pause
GOTO:EOF
:next
set "newname=%~nx1"

set "newname=%newname:XXXX=zzzz%"


echo ren %1 "%newname%

当我运行上述内容时,它会用zzzz的

替换XXXX

当我将set "newname=%newname:XXXX=zzzz%"更改为set "newname=%newname:XXXX=%host%"时,它只会删除X.

1 个答案:

答案 0 :(得分:2)

如果您使用延迟扩展会怎样?

@Echo Off
SetLocal EnableDelayedExpansion
Set "Host=%COMPUTERNAME:~4,2%"
For /F "Delims=" %%A In ('Dir /B/A-D/ON') Do (Set "NewName=%%~nA"
    Echo Ren "%%~A" "!NewName:XXXX=%Host%!%%~xA"
Pause
GoTo :EOF