通过批处理以UTF-8格式保存文本

时间:2014-12-29 16:37:22

标签: batch-file encoding utf-8

我仍在研究.m3u播放列表文件的转换器,它们将它们从Windows Media Player生成的格式转换为Teamspeak 3插件“Soundboard”接受的格式。

主转换器现在已经完成,我遇到了最后一个问题: 使用批处理脚本编写新代码时,使用echo a-lot-of-text-and-code >> 3.txt将其保存到ANSI编码文件中,看起来该插件只能打开UTF-8编码文件。

有没有办法只使用Batch将3.txt的编码从ANSI更改为UTF-8?

问候,乔

1 个答案:

答案 0 :(得分:2)

需要进行一些实验,但我成功调整了Simon Sheppard's UCS-2 encode method以将文件编码为带有批处理的UTF-8。

@echo off
setlocal

:: utf8.bat infile outfile
:: convert infile to utf8 and save as outfile

if not exist "%~1" goto usage
if "%~2"=="" goto usage

set "infile=%~f1"
set "outfile=%~f2"

:: store current console codepage to var
for /f "tokens=2 delims=:" %%I in ('chcp') do set "_codepage=%%I"

:: temporarily change console codepage to UTF-8
>NUL chcp 65001

:: set byte order mark for outfile
>"%outfile%" set /p "=" <NUL

:: dump infile to outfile encoded as UTF-8
>>"%outfile%" type "%infile%"

:: restore console to original codepage
>NUL chcp %_codepage%

goto :EOF

:usage
echo Usage: %~nx0 infile outfile

此脚本本身需要以ANSI编码保存。