我有一個要求,我的批處理腳本應該找到批處理的輸入文件的編碼類型是否是UTF-8?任何人都可以告訴我是否可以找到編碼類型或不在窗口??使用批處理腳本找到編碼類型
1
A
回答
4
與certutil
您可以轉儲十六進制格式的文件。 UTF-8文件以0xEF,0xBB,0xBF
開頭。所以:
certutil -dump my.file.txt | find "ef bb bf" && echo this is utf-8
你可以把這個在FOR /F
循環,以確保只有第一線進行處理。
更新:
原來的certutil
的-dump
選項buggy。所以我需要使用它需要一個臨時文件-encodehex
:
@echo off
:detect_encoding
setLocal
if "%1" EQU "-?" (
endlocal
call :help
exit /b 0
)
if "%1" EQU "-h" (
endlocal
call :help
exit /b 0
)
if "%1" EQU "" (
endlocal
call :help
exit /b 0
)
if not exist "%1" (
echo file does not exists
endlocal
exit /b 54
)
if exist "%1\" (
echo this cannot be used against directories
endlocal
exit /b 53
)
if "%~z1" EQU "0" (
echo empty files are not accepted
endlocal
exit /b 52
)
set "file=%~snx1"
del /Q /F "%file%.hex" >nul 2>&1
certutil -f -encodehex %file% %file%.hex>nul
rem -- find the first line of hex file --
for /f "usebackq delims=" %%E in ("%file%.hex") do (
set "f_line=%%E" > nul
goto :enfdor
)
:enfdor
del /Q /F "%file%.hex" >nul 2>&1
rem -- check the BOMs --
echo %f_line% | find "ef bb bf" >nul && echo utf-8 &&endlocal && exit /b 1
echo %f_line% | find "ff fe 00 00" >nul && echo utf-32 LE &&endlocal && exit /b 5
echo %f_line% | find "ff fe" >nul && echo utf-16 &&endlocal && exit /b 2
echo %f_line% | find "fe ff 00" >nul && echo utf-16 BE &&endlocal && exit /b 3
echo %f_line% | find "00 00 fe ff" >nul && echo utf-32 BE &&endlocal && exit /b 4
echo ASCII & endlocal & exit /b 6
endLocal
goto :eof
:help
echo.
echo %~n0 file - Detects encoding of a text file
echo.
echo for each encoding you will recive a text responce with a name and a errorlevel codes as follows:
echo 1 - UTF-8
echo 2 - UTF-16 BE
echo 3 - UTF-16 LE
echo 4 - UTF-32 BE
echo 5 - UTF-32 LE
echo 6 - ASCII
echo for empty files you will receive error code 52
echo for directories you will receive error code 53
echo for not existing file you will receive error code 54
goto :eof
相關問題
- 1. 批處理腳本編程
- 2. 使用批處理腳本
- 3. 使用批處理腳本
- 4. 批處理腳本
- 5. 批處理腳本
- 6. 如何從批處理腳本中運行批處理腳本?
- 7. 批處理腳本後停止向其他批處理腳本
- 8. 批處理腳本編輯文件名
- 9. Windows批處理腳本url解碼
- 10. Windows批處理腳本使用FOR
- 11. 在批處理腳本中使用VMMap
- 12. 如何使用批處理腳本
- 13. 如何使用批處理腳本
- 14. 交錯批處理腳本處理
- 15. 批處理腳本來處理文件
- 16. 退出調用另一個批處理腳本的批處理腳本
- 17. 使用批處理腳本逐行解析文本文件(批處理文件)
- 18. 在Windows批處理腳本
- 19. Perforce批處理腳本
- 20. 從批處理腳本
- 21. Windows批處理腳本 - 在
- 22. Serverside FTP批處理腳本
- 23. 通過批處理腳本
- 24. 準備批處理腳本
- 25. xcopy的批處理腳本
- 26. 批處理腳本問題
- 27. 在批處理腳本
- 28. 在Windows批處理腳本
- 29. 批處理腳本問題
- 30. FFmpeg的批處理腳本
究竟什麼是你想去做?我問這是因爲在處理文件之前你可以很容易地轉換文件,但實際上確定它們是什麼編碼會有點困難。 – 2013-04-26 13:17:04
感謝您的答覆。如果文件採用UTF-8格式,我可以按原樣使用該文件。但是當文件格式不同時,我需要將文件轉換爲UTF-8並需要進行處理。爲此我需要知道文件格式。 – satish 2013-04-26 13:28:08