操作系统:Windows 7 SP1
我使用以下命令在cmd.exe
中创建了一个空白文本文件:
echo 2> .gitignore
该命令将
std::cerr
(在本例中为空输出)重定向到.gitignore
文件中。结果文件采用ANSI
编码,但我需要UTF-8
。我能否指定必要的编码(UTF-8
)进行>
操作?操作系统:Windows 7 SP1
我使用以下命令在cmd.exe
中创建了一个空白文本文件:
echo 2> .gitignore
std::cerr
(在本例中为空输出)重定向到.gitignore
文件中。结果文件采用ANSI
编码,但我需要UTF-8
。我能否指定必要的编码(UTF-8
)进行>
操作?批处理文件无法通过输出重定向实现。
使用内置工具唯一的方式是调用powershell:
powershell -c "[io.file]::WriteAllText('.gitignore','',[System.Text.Encoding]::UTF8)"
纯批处理方案,基于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
混合批处理 - 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();
<!-- : 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>
使用纯批处理创建带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
)
<nul SET /P "=123"> output.txt
然后在您喜欢的HEX编辑器中将123替换为EF BB BF字节。
要稍后编辑此.bat/.cmd文件,不应使用Windows的Notepad.exe,因为它会在“保存为ASCII”模式下将BOM字节转换为问号(?
)(或者在“保存为UTF-8”模式下它会向脚本文件本身添加不必要的BOM)。
相反,可以使用Notepad++并选择“UTF-8(无BOM)”模式。
我有一个带有BOM的空文本文件,我将其复制,然后将我需要的内容附加到此文件中。
copy empty-bom.txt .gitignore
echo stuff>>.gitignore
我更喜欢这个解决方案,因为它比生成BOM的所有其他解决方案更易读、更易理解。
这将给您 utf 16,在 cmd
上使用 /u
开关启动
cmd /u /c type ansi.txt > uni.txt
/u
使内部命令输出UTF16。
chcp 65001
(utf-8)命令。 - jessehouwingOut-File
命令来实现。 - n0rd