您的问题不在于批处理变量:从命令行可以正常工作:
for %i in (*) do ren "%~i" "test_%~i"
但是,从以下内容可以看出:
for /f "delims=" %i in ('dir /b /a-d') do @echo ren "%~i" "test2_%~i"
dir /b
正在将破折号更改为连字符,因此ren
命令显然找不到要更改的文件。
对于您的示例,您应该找到:
for /d %%i in (*) do (
and
for %%j in (*.xl*) do ...
应该可以正常工作。
如果您需要dir /b
由于其他原因,我现在没有看到解决方案。
(I had a convoluted attempt exchanging all hyphens for question marks, using the "Environment variable substitution" and "delayed environment variable expansion" as described in SET /?
and CMD /?
, allowing any character to match, and then again use ren
pattern matching to ignore the problem.
I.e.
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "delims=" %%I in ('dir /b /a-d') do (
Set K=%%I
ren "!K:-=?!" "test2_!K:-=?!"
)
but ren * x*
replaces the start of the files with x
, so the above replaces the hyphens with the content at that location before test_
was inserted.
So the best this approach can do is convert the em dashes to hyphens with:
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "delims=" %%I in ('dir /b /a-d') do (
Set K=%%I
ren "!K:-=?!" "test2_!K!"
)
)
并确认它是输出dir /b
这就是问题所在:在命令行上:
dir /b *—* > test.txt
在那里—
是一个破折号,只会列出带有破折号的文件,但是,在输出文件中,例如Notepad test.txt
,您只会找到连字符,而不会找到破折号。
顺便说一句,我已经在 Windows 8.1 上完成了所有这些测试VER
显示为Microsoft Windows [Version 6.3.9600]
.
(As I mention above I did have ren * x*
in this answer, but that replaces the first character with x
rather than insert it, which I always thought ren
did!)