批处理文件,从文件夹中删除前导空格在 Win10 中不起作用,但在 WinXP 中起作用



我是编写批处理程序的新手。我有数千个名称中包含前导空格字符的文件夹,我需要删除空格。通过仔细阅读堆栈溢出站点,我整理了一些在WinXP中按预期执行的代码,但在我的Win10系统上没有。

@echo off
for /d %%A in (" *") do @for /f "tokens=*" %%B in ("%%A") do @ren "%%A" "%%B"

上面的代码片段在 WinXP 中工作得很好。例如,文件夹可能命名为"L700",但在运行代码后名称正确更改为"L700"。但是,在我的 Win10 系统上,上面的代码不会更改文件名的任何内容。

完整代码如下:

@echo off
rem Prepare environment
setlocal enableextensions disabledelayedexpansion
rem configure where to start
set "root=C:Test"
rem For each file under root that match indicated pattern
for /r "%root%" %%f in (*,*,*.xlsm) do (
rem Split the file name in tokens using the comma as delimiter
for /f "tokens=2 delims=," %%p in ("%%~nf") do (
rem Test if the file is in the correct place
for %%d in ("%%~dpf.") do if /i not "%%~p"=="%%~nd" (
rem if it is not, move it where it should be
if not exist "%%~dpf%%~p"  md "%%~dpf%%~p"
move "%%~ff" "%%~dpf%%~p"
)
)
)
rem line below removes space from beginning of folder name
for /d %%A in (" *") do @for /f "tokens=*" %%B in ("%%A") do @ren "%%A" "%%B"
@ECHO Off
SETLOCAL
SET "sourcedir=U:sourcedirt w o"
FOR /d  %%a IN ("%sourcedir% *") DO (
ECHO "%%a"
for /f "tokens=*" %%b in ("%%~nxa") do ECHO ren "%%a" "%%~nxb"
)
GOTO :EOF

ren命令已被撤防,只是为了安全起见echo,直到验证脚本操作。

我无法访问XP系统,但我很惊讶它在XP上运行。问题是%%a包含完整路径,因此您只需要为重命名和前导空格抑制机制选择名称和扩展名。

最新更新