How to deal with an em dash in a filename

旧城冷巷雨未停 提交于 2021-01-27 22:47:48

问题


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

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?


回答1:


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

and

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

should work fine.

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

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

)

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

dir /b *—* > 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.

BTW I've done all this testing on Windows 8.1 which VER displays as 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!)



来源:https://stackoverflow.com/questions/22677677/how-to-deal-with-an-em-dash-in-a-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!