Rob van der Woude's Scripting Pages

Batch How To ...

Check File Encoding

Recently, while searching for a way to detect Unicode vs. ANSI encoding in VBScript, I found this brilliantly simple batch solution by jaclaz:

@ECHO OFF
:: Based on code by "jaclaz" on MSFN.ORG
:: http://www.msfn.org/board/topic/158633-how-to-check-text-file-encoding-from-command-line/#comment-1014056
IF "%~1"=="" (
	ECHO Usage:  %~n1  textfilename
	GOTO:EOF
)
FOR /F %%A IN (%1) DO (
	ECHO ANSI
	GOTO:EOF
)
ECHO Unicode

It is based on the fact that a FOR /F loop will abort if the text file contains ASCII 0 characters.
This code will work:

FOR /F %%A IN (%1) DO (ECHO ANSI&GOTO:EOF)

However, the following code won't:

FOR /F %%A IN ('TYPE %1') DO (ECHO ANSI&GOTO:EOF)

That's because TYPE already "filtered out" the ASCII 0 characters.

 


page last modified: 2017-07-25; loaded in 0.0017 seconds