问题描述
我在Windows shell中的chcp 65001
命令有问题.
I have a problem with chcp 65001
command in Windows shell.
我需要在文件夹中生成文件列表.所以我运行了cmd.exe,输入了
I need to generate a list of files in a folder.So I ran cmd.exe, typed
cd folder
dir /B /O:N > list_of_files.txt
它有效,但是我在某些文件名中使用特殊的非ASCII字符时遇到了问题.所以我加了chcp 65001
It worked, but I had a problem with special, non-ASCII characters which are in some file names.So I addedchcp 65001
一切正常,但是当我将这些命令放入.bat文件时,该脚本不起作用.
Everything worked, but when I put these commands into a .bat file, the script doesn't work.
所以
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
生成列表,但使用默认编码:/.
generates the list, but with the default encoding :/.
所有内容都可以在cmd.exe中使用,但不能在.bat文件中使用.
Everything works in cmd.exe, but not in .bat files.
我已经阅读了以下主题:stackoverflow.com/问题2182568/batch-script-is-not-exected-if-chcp-被调用,但没有帮助.
I've read the topic: stackoverflow.com/questions/2182568/batch-script-is-not-executed-if-chcp-was-called, but it didn't help.
我部分解决了我的问题,将chcp 65001
更改为chcp 1250
,因为所有字符都在此编码中.但这实际上并不能解决问题.
I partially solved my problem, changing chcp 65001
to chcp 1250
because all characters were in this encoding. But actually this doesn't answer the question.
推荐答案
使用cmd /U
.参见 http://ss64.com/nt/cmd.html :
-
/A
输出ANSI字符 -
/U
输出UNICODE字符(UCS-2小端)
/A
Output ANSI characters/U
Output UNICODE characters (UCS-2 Little Endian)
这是我的尝试(当然,在cmd /A
下启动):
Here's my attempt (launch it under cmd /A
, of course):
@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
),抱歉;使用另一种方法获取 pure Utf-8字节顺序标记:
Output. Still invalid first line (that hexadecimal 0D0A
), sorry; use another method to get pure Utf-8 byte order mark:
==>cmd /A /C D:\bat\SO\UTF8BOM32182619.bat
cpANSI_OoCcSsUu.txt
cpANSI_ÖöÇ窺Üü.txt
escrzyaie.txt
ěščřžýáíé.txt
list_of_files.txt
==>
这篇关于chcp 65001和一个.bat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!