加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

批处理文件 – chcp 65001和.bat文件

发布时间:2020-12-14 04:21:21 所属栏目:Windows 来源:网络整理
导读:我在 Windows shell中遇到chcp 65001命令的问题. 我需要生成一个文件夹中的文件列表. 所以我运行cmd.exe,键入 cd folderdir /B /O:N list_of_files.txt 它工作,但我遇到了一些特殊的非ASCII字符的问题,这些字符在某些文件名中. 所以我补充道 chcp 65001 一切
我在 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:batSOUTF8BOM32182619.bat
?
cpANSI_OoCcSsUu.txt
cpANSI_??????üü.txt
escrzyaie.txt
ě????yáíé.txt
list_of_files.txt

==>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读