且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理文件名中的破折号

更新时间:2022-02-24 08:13:54

您的问题不在于批处理变量:从命令行这工作正常:

Your problem is not with the batch variables: from the command line this works fine:

for %i in (*) do ren "%~i" "test_%~i"

但是,从以下可以看出:

but, as can be seen from:

for /f "delims=" %i in ('dir /b /a-d') do @echo ren "%~i" "test2_%~i"

dir/b 正在将破折号更改为连字符,因此 ren 命令显然找不到要更改的文件.

dir /b is changing the em dash to a hyphen, and so the ren command clearly won't find the file to change.

对于您的示例,您应该找到:

For your examples you should find:

for /d %%i in (*) do (

for %%j in (*.xl*) do ...

应该可以正常工作.

如果您出于其他原因需要 dir/b,我现在看不到解决方案.

If you need the dir /b for other reasons, I don't see a solution right now.

(我曾尝试使用 SET/? 中所述的环境变量替换"和延迟环境变量扩展"将所有连字符替换为问号,这是一个令人费解的尝试CMD/?,允许任意字符匹配,然后再次使用ren模式匹配忽略问题.

(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.

SETLOCAL ENABLEDELAYEDEXPANSION

for /f "delims=" %%I in ('dir /b /a-d') do (
 Set K=%%I
 ren "!K:-=?!" "test2_!K:-=?!"
)

but ren * x* replacesx 文件的开头,所以上面用内容替换连字符在插入 test_ 之前的那个位置.

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.

所以这种方法可以做的***的事情是将破折号转换为连字符:

SETLOCAL ENABLEDELAYEDEXPANSION

for /f "delims=" %%I in ('dir /b /a-d') do (
 Set K=%%I
 ren "!K:-=?!" "test2_!K!"
)

)

并确认是 dir/b 的输出是问题所在:在命令行上:

And confirming it is the output of dir /b that is the problem: on the command line:

dir /b *—* > test.txt

其中 是一个长破折号,只会列出带有长破折号的文件,但是,在输出文件中,例如Notepad test.txt,你只会找到连字符,没有破折号.

where that is an em dash, will only list the files with em dashes, but, in the output file, e.g. Notepad test.txt, you'll only find hyphens, and no em dashes.

顺便说一句,我已经在 Windows 8.1 上完成了所有这些测试,VER 显示为 Microsoft Windows [Version 6.3.9600].

BTW I've done all this testing on Windows 8.1 which VER displays as Microsoft Windows [Version 6.3.9600].

(正如我上面提到的,我在这个答案中确实有 ren * x* ,但是x 替换了第一个字符> 而不是插入它,我一直认为 ren 做到了!)

(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!)