编写一个仅包含 UTF-8 BOM 的空文件

问题描述 投票:0回答:7

操作系统:Windows 7 SP1

我使用以下命令在

cmd.exe
中创建了一个空文本文件:

echo 2> .gitignore

该命令将

std::cerr
(本例中为空输出)重定向到
.gitignore
文件中。结果文件具有
ANSI
编码,但我需要
UTF-8
。我可以为
UTF-8
操作指定必要的编码 (
>
) 吗?

windows shell powershell batch-file cmd
7个回答
5
投票

通过批处理文件输出重定向是不可能的。

使用内置实用程序执行此操作的唯一方法是调用 powershell:

powershell -c "[io.file]::WriteAllText('.gitignore','',[System.Text.Encoding]::UTF8)"

3
投票

纯批处理解决方案,基于 dbenham 从批处理生成几乎任何字符,包括 TAB

@echo off

(set LF=^
%=empty=%
)

::Create variables to store BOM bytes
call :hexprint "0xEF" EF
call :hexprint "0xBB" BB
call :hexprint "0xBF" BF

<nul SET /P "=%EF%%BB%%BF%"> output.txt
exit /b

:hexPrint  string  [rtnVar]
  for /f eol^=^%LF%%LF%^ delims^= %%A in (
    'forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(%~1"'
  ) do if "%~2" neq "" (set %~2=%%A) else echo(%%A
exit /b

另请参阅 在 Windows 批处理中将十六进制值写入文件


1
投票

创建一个 .bat/.cmd 文件,例如:

<nul SET /P "=123"> output.txt

然后在您喜欢的十六进制编辑器中将 123 替换为 EF BB BF 字节。

稍后要编辑此 .bat/.cmd 文件,不应使用 Window 的 Notepad.exe,因为它会在“另存为 ASCII”模式(或者在“保存”模式下)将 BOM 字节转换为问号 (

?
)作为 UTF-8”模式,它会将不需要的 BOM 添加到脚本文件本身)。 相反,我们可以使用“UTF-8(无 BOM)”模式的 Notepad++。


1
投票

混合批处理 - JScript 解决方案。只需另存为批处理文件即可正常运行

@if (@CodeSection == @Batch) @then

@echo off
cscript //e:jscript //nologo "%~f0" %1
exit /b

@end

// JScript Section

var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.CreateTextFile(WScript.Arguments.Item(0), true);

file.Write(String.fromCharCode(239));
file.Write(String.fromCharCode(187));
file.Write(String.fromCharCode(191));
file.Close();

同上,但是混合批处理 - VBS

<!-- : Begin batch script
@echo off
cscript //nologo "%~f0?.wsf" %1
exit /b

----- Begin wsf script --->
<job><script language="VBScript">
    Set fso  = CreateObject("Scripting.FileSystemObject")
    Set file = fso.CreateTextFile(WScript.Arguments.Item(0), true)

    file.Write Chr(239)
    file.Write Chr(187)
    file.Write Chr(191)
    file.Close
</script></job>

1
投票

纯批量创建带 BOM 的空 UTF-8 文件:

set _FILE=output.txt
chcp 437 > nul
forfiles /c "cmd /c <nul set /p=0xEF0xBB0xBF>\"%_FILE%\"" > nul
chcp 65001 > nul

并添加行:

>> "%_FILE%" (
    echo Line 1
    echo Line 2
)

0
投票

我有一个带有 BOM 的空文本文件,我复制该文件,然后将我需要的内容附加到该文件中。

copy empty-bom.txt .gitignore
echo stuff>>.gitignore

我更喜欢这个解决方案,因为它比生成 BOM 的所有其他解决方案更具可读性和可理解性。


-1
投票

这将为您提供 utf 16,使用

cmd
开关
 开始 
/u

cmd /u /c type ansi.txt > uni.txt

/u
使内部命令输出UTF16。

© www.soinside.com 2019 - 2024. All rights reserved.