我在
Windows shell中遇到chcp 65001命令的问题.
我需要生成一个文件夹中的文件列表.
所以我运行cmd.exe,键入
cd folder dir /B /O:N > list_of_files.txt
它工作,但我遇到了一些特殊的非ASCII字符的问题,这些字符在某些文件名中.
所以我补充道
chcp 65001
一切正常,但当我将这些命令放入.bat文件时,脚本不起作用.
所以
cd folder chcp 65001 dir /B /O:N > list_of_files.txt
不生成列表.
和
cd folder chcp 65001 && dir /B /O:N > list_of_files.txt
以及
cd folder chcp 65001 > nul && dir /B /O:N > list_of_files.txt
生成列表,但使用默认编码:/.
一切都在cmd.exe中,但不在.bat文件中.
我已经阅读了主题:stackoverflow.com/questions/2182568/batch-script-is-not-executed-if-chcp-was-called,但它没有帮助.
编辑:
我部分解决了我的问题,将chcp 65001更改为chcp 1250,因为所有字符都处于此编码状态.但实际上这并没有回答这个问题.
使用cmd / U.见
http://ss64.com/nt/cmd.html:
Most common text files are ANSI,use these switches when you need to
convert the character set. These options will affect 07001 to a file:
/A
Output ANSI characters/U
Output UNICODE characters (UCS-2 Little Endian)
这是我的尝试(当然是在cmd / A下启动):
@ECHO OFF >NUL SETLOCAL EnableExtensions :: create a UNICODE file with Byte Order Mark using `wmic` chcp 852 >NUL >list_of_files.txt wmic os get localdatetime :: store a line with BOM to a variable :: although FINDSTR does not support UTF-16 files :: it will read first three bytes at least for /F "delims=" %%G in (' findstr "^" list_of_files.txt ') do set "UTF8BOM=%%G" :: write BOM only* to a file (* echo writes hexadecimal value FFFE0D0A) :: the `<NUL set /p =text` trick does not work: chokes down leading `FF` >list_of_files.txt echo(%UTF8BOM:~0,2% chcp 65001 >NUL :: add CRLF in Unicode (hexadecimal 0D000A00) >>list_of_files.txt cmd /U /C echo( :: add result of `dir /B /O:N` in Unicode >>list_of_files.txt cmd /U /C dir /B /O:N :: check the result: still invalid first line,see output type list_of_files.txt chcp 852 >NUL
输出.仍然无效的第一行(即十六进制0D0A),对不起;使用另一种方法获得纯Utf-8字节顺序标记:
==>cmd /A /C D:\bat\SO\UTF8BOM32182619.bat cpANSI_OoCcSsUu.txt cpANSI_ÖöÇ窺Üü.txt escrzyaie.txt ěščřžýáíé.txt list_of_files.txt ==>