我编写了一个 BAT 文件来删除文件名开头的“@”。(请不要问为什么!...为什么是 Windows,为什么是 CMD...):)
这是 BAT 文件:
IF EXIST "%~1" (
FOR /F %%F IN ("%~1") DO (
CD /D "%%~dpF"
IF ERRORLEVEL 1 (
ECHO. Failed to CD to folder: %%~dpF
) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%%~nxF
IF "%A:~0,1%"=="@" (
ECHO. RENAME "%A%" "%A:~1%"
RENAME "%A%" "%A:~1%"
REM RENAME "%%A%" "%%A:~1%"
) ELSE (
ECHO. File does not start with @: %A%
)
ENDLOCAL
)
)
) ELSE (
ECHO. File not found: %1
)
pause
当我从 DOS 窗口的命令行运行它时,它似乎起作用了:
18:54:04.97>dir /b *foo*
@foo.txt
18:54:07.97>test@ "%cd%\@foo.txt"
18:54:18.75>IF EXIST "C:\Users\me\lbin\@foo.txt" (FOR /F %F IN ("C:\Users\me\lbin\@foo.txt") DO (
CD /D "%~dpF"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: %~dpF ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%~nxF
IF "@" == "@" (
ECHO. RENAME "@foo.txt" "foo.txt"
RENAME "@foo.txt" "foo.txt"
REM RENAME "%Afoo.txt"
) ELSE (ECHO. File does not start with @: @foo.txt )
ENDLOCAL
)
) ) ELSE (ECHO. File not found: "C:\Users\me\lbin\@foo.txt" )
18:54:18.77>(
CD /D "C:\Users\me\lbin\"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: C:\Users\me\lbin\ ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET [email protected]
IF "@" == "@" (
ECHO. RENAME "@foo.txt" "foo.txt"
RENAME "@foo.txt" "foo.txt"
REM RENAME "%Afoo.txt"
) ELSE (ECHO. File does not start with @: @foo.txt )
ENDLOCAL
)
)
RENAME "@foo.txt" "foo.txt"
18:54:18.80>pause
Press any key to continue . . .
18:54:20.74>
但是当我从 SENDTO 菜单中的快捷方式运行 BAT 文件时,操作substring
无法正确展开 - 具体来说,“IF”无法正确展开(IF "%A:~0,1%"=="@" (
) - 看到了吗?...
C:\Users\me\lbin>IF EXIST "C:\Users\me\lbin\@foo.txt" (FOR /F %F IN ("C:\Users\me\lbin\@foo.txt") D
O (
CD /D "%~dpF"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: %~dpF ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%~nxF
IF "~0,1" == "@" (
ECHO. RENAME "" "~1"
RENAME "" "~1"
REM RENAME "%A~1"
) ELSE (ECHO. File does not start with @: )
ENDLOCAL
)
) ) ELSE (ECHO. File not found: C:\Users\me\lbin\@foo.txt )
C:\Users\me\lbin>(
CD /D "C:\Users\me\lbin\"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: C:\Users\me\lbin\ ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET [email protected]
IF "~0,1" == "@" (
ECHO. RENAME "" "~1"
RENAME "" "~1"
REM RENAME "%A~1"
) ELSE (ECHO. File does not start with @: )
ENDLOCAL
)
)
File does not start with @:
C:\Users\me\lbin>pause
Press any key to continue . . .
有想法吗?
答案1
延迟扩张将导致变量在执行时而不是在解析时扩展,此选项通过命令打开
SETLOCAL
。当延迟扩展生效时,可以使用!variable_name!
(除了正常的%variable_name%
)引用变量
因此,分别使用!A!
、!A:~0,1!
和!A:~1!
代替%A%
、%A:~0,1%
和 ,%A:~1%
如下所示:
SETLOCAL ENABLEEXTENSIONS
SET A=%%~nxF
IF "!A:~0,1!"=="@" (
ECHO. RENAME "!A!" "!A:~1!"
RENAME "!A!" "!A:~1!"
) ELSE (
ECHO. File does not start with @: !A!
)
ENDLOCAL