Incorrect encoding after redirecting `dir` output to a file

感情迁移 提交于 2020-01-01 09:46:14

问题


I run this code on Windows cmd.exe in Europe and I use local settings here, for my language. So I use diacritics in names of the directories.

I try to list names of the directories and they are displayed correctly. Then I save them into file, but when I open it in notepad, the diacritics is not readable: for example, instead of Střední Čechy I have Stýednˇ ¬echy.

What did I do wrong and how can I correct it?

@echo off
del directories.conf
FOR /F "delims=!" %%R IN ('dir * /b /a:d /o:n') DO (

 IF EXIST "%%R\scenery" ( 
  echo %%R
  echo %%R >> directories.conf
 ) ELSE (ECHO NOT INCLUDED %%R)

)
Echo Directory list created...
pause

回答1:


Try starting cmd.exe with /u switch. That will cause cmd to write in UTF-16.

Also you need to switch to code page 1250 (ANSI for Central Europe) using chcp 1250.

You can do it inside your batch script. I made one for you. The structure is:

.\Jižní Morava
.\Jižní Morava\scenery
.\Pelhřimov
.\Pelhřimov\scenery
.\Nic moc výlet
.\Střední Čechy
.\Střední Čechy\scenery

And the script:

@echo off

if _%1_==_main_ (
    call :main
) else (
    cmd /u /c "%0 main"
)
goto :eof

:main
    chcp 1250
    del directories.conf
    for /F "delims=!" %%R in ('dir * /b /a:d /o:n') do (
        if exist %%R\scenery (
            echo %%R
            echo %%R >> directories.conf
        ) else (
            echo not included: %%R
        )
    )
    echo Directory list created...
    pause
goto :eof

Also I recommend you to read andrewdotn's great answer to a related question.




回答2:


As an alternative solution (if the file is already generated) you can just re-encode your file.

Notepad++ has this feature:

  • Go to Encoding > Character sets
  • Select the appropriate character set that has a graceful render
  • Go back to Encoding > Character sets
  • Select Convert to UTF-8
  • Save your file


来源:https://stackoverflow.com/questions/9905740/incorrect-encoding-after-redirecting-dir-output-to-a-file

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