我想替换一个变量的子串,以前存储在for循环中的一个变量上,我试着像这样做,但它不起作用:
setlocal EnableDelayedExpansion
set checkVar=abcd
FOR %%Y IN (*.pdf) DO (
SET meu=%%Y
CALL SET meuWithoutChar=!meu:%%%checkVar%%%=!
ECHO meuWithoutChar=!meuWithoutChar!
)
例如这里if %%Y==blepabcdnnnn.pdf
;我想在输出上有meuWithoutChar=blepnnnn.pdf
谢谢你提前
您对延迟扩展的概念以及使用CALL进行额外的扩展阶段感到有点困惑。以下是示例。我只是使用你的单个文件示例。您可以将其更改回使用通配符。
CALL示例
@echo off
set checkVar=abcd
FOR %%Y IN (blepabcdnnnn.pdf) DO (
SET "meu=%%Y"
CALL SET "meuWithoutChar=%%meu:%checkVar%=%%"
CALL ECHO meuWithoutChar=%%meuWithoutChar%%
)
pause
延迟扩张
@echo off
setlocal Enabledelayedexpansion
set checkVar=abcd
FOR %%Y IN (blepabcdnnnn.pdf) DO (
SET "meu=%%Y"
SET "meuWithoutChar=!meu:%checkVar%=!"
ECHO meuWithoutChar=!meuWithoutChar!
)
pause
作为Squashmans答案的补充/延伸。 仅循环访问必要的文件并忽略文件的扩展名。
没有延迟扩张:
@Echo Off
SetLocal DisableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
Call Set "objNewFile=%%objFileName:%strChr%=%%%%~xA"
Call Echo %%%%objNewFile%%%%=%%objNewFile%%)
Pause
使用完整脚本延迟扩展(将出现包含!
文件名的问题):
@Echo Off
SetLocal EnableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
Set "objNewFile=!objFileName:%strChr%=!%%~xA"
Echo %%objNewFile%%=!objNewFile!)
Pause
切换延迟扩展,(保护包含!
的文件名):
@Echo Off
SetLocal DisableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
SetLocal EnableDelayedExpansion
Set "objNewFile=!objFileName:%strChr%=!%%~xA"
Echo %%objNewFile%%=!objNewFile!
EndLocal)
Pause