本文介绍了如何处理文件名中的破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在装有 Windows 7 的 PC 上,我使用一个简单的批处理脚本来重命名一些 Excel 文件,并在其父文件夹名称之前:

On a PC with Windows 7, I'm using a simple batch script to rename some Excel files, pre-pending their parent folder name:

for /f "delims=" %%i in ('dir /b /AD') do (
    cd "%%i"
    for /f "delims=" %%j in ('dir /b *.xl*') do ren "%%~j" "%%i_%%~j"
    cd..
)

我注意到有些文件产生了错误,系统找不到指定的文件."这些文件的文件名中都有一个破折号 (—).在我使用 Windows 资源管理器将长破折号更改为常规连字符 (-) 后,脚本在这些文件上运行良好.

I noticed that some files generated an error, "System cannot find the specified file." These files all had an em dash (—) in the filename. After I changed the em dash to a regular hyphen (-), using Windows Explorer, the script worked fine on these files.

我如何帮助编写这些文件的重命名脚本?

How can I help script the rename of these files?

推荐答案

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

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.

SETLOCAL ENABLEDELAYEDEXPANSION

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

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

这篇关于如何处理文件名中的破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:51
查看更多