Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write an empty file with just the UTF-8 BOM

OS: Windows 7 SP1

I created an empty text file in the cmd.exe using the below command:

echo 2> .gitignore

The command redirects std::cerr (empty output in this case) into the .gitignore file. The result file has ANSI encoding, but I need UTF-8. Can I point the necessary encoding (UTF-8) for the > operation?

like image 748
Andrey Bushman Avatar asked Aug 02 '15 12:08

Andrey Bushman


People also ask

How do you create an empty file?

To create an empty file on the Windows Command line, you can utilize Command Prompt or PowerShell. On Command Prompt, many commands are available to create a new file or empty file, such as “cd.”, “copy nul”, ”break”, “echo.”, “type nul”, and “call”.

Should you use UTF-8 with BOM?

The Unicode Standard permits the BOM in UTF-8, but does not require or recommend its use. Byte order has no meaning in UTF-8, so its only use in UTF-8 is to signal at the start that the text stream is encoded in UTF-8, or that it was converted to UTF-8 from a stream that contained an optional BOM.

What does UTF-8 with BOM mean?

The UTF-8 file signature (commonly also called a "BOM") identifies the encoding format rather than the byte order of the document. UTF-8 is a linear sequence of bytes and not sequence of 2-byte or 4-byte units where the byte order is important.


2 Answers

It's not possible via batch-file output redirection.

The only way to do it with the built-in utilities is to invoke powershell:

powershell -c "[io.file]::WriteAllText('.gitignore','',[System.Text.Encoding]::UTF8)"
like image 187
wOxxOm Avatar answered Sep 22 '22 01:09

wOxxOm


Pure batch solution, based on Generate nearly any character, including TAB, from batch by dbenham

@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
like image 35
phuclv Avatar answered Sep 18 '22 01:09

phuclv