你知道我可以以编程方式或通过脚本将一组以 ansi 字符编码保存的文本文件转换为 unicode 编码的方法吗?
当我用记事本打开文件并选择将其保存为 unicode 文件时,我想做同样的事情。
你知道我可以以编程方式或通过脚本将一组以 ansi 字符编码保存的文本文件转换为 unicode 编码的方法吗?
当我用记事本打开文件并选择将其保存为 unicode 文件时,我想做同样的事情。
这可能对您有用,但请注意它会抓取当前文件夹中的每个文件:
Get-ChildItem | Foreach-Object { $c = (Get-Content $_); `
Set-Content -Encoding UTF8 $c -Path ($_.name + "u") }
为简洁起见,使用别名也是如此:
gci | %{ $c = (gc $_); sc -Encoding UTF8 $c -Path ($_.name + "u") }
Steven Murawski 建议Out-File
改用。两个 cmdlet 之间的区别如下:
Out-File
将尝试格式化它收到的输入。Out-File
的默认编码是基于 Unicode 的,而Set-Content
使用系统的默认编码。这是一个假设文件test.txt
在任何一种情况下都不存在的示例:
PS> [system.string] | Out-File test.txt
PS> Get-Content test.txt
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
# test.txt encoding is Unicode-based with BOM
PS> [system.string] | Set-Content test.txt
PS> Get-Content test.txt
System.String
# test.txt encoding is "ANSI" (Windows character set)
事实上,如果您不需要任何特定的 Unicode 编码,您也可以执行以下操作将文本文件转换为 Unicode:
PS> Get-Content sourceASCII.txt > targetUnicode.txt
Out-File
是一种“带有可选参数的重定向运算符”。
最简单的方法是 Get-Content 'path/to/text/file' | 输出文件“名称/文件/文件”。
Out-File 有一个 -encoding 参数,默认为 Unicode。
如果你想编写一批脚本,你可以做类似的事情
$files = get-childitem 'directory/of/text/files'
foreach ($file in $files)
{
get-content $file | out-file $file.fullname
}
将 System.IO.StreamReader(读取文件内容)类与 System.Text.Encoding.Encoding(创建进行编码的 Encoder 对象)基类一起使用。
您可以创建一个新的文本文件并将原始文件中的字节写入新文件,在每个原始字节之前放置一个“\0”(假设原始文本文件是英文的)。
伪代码...
昏暗系统、文件、内容、newFile、oldFile
常量 ForReading = 1,ForWriting = 2,ForAppending = 3 常量 AnsiFile = -2,UnicodeFile = -1
设置 system = CreateObject("Scripting.FileSystemObject...
设置文件 = system.GetFile("text1.txt")
设置 oldFile = file.OpenAsTextStream(ForReading, AnsiFile)
内容 = oldFile.ReadAll()
oldFile.关闭
system.CreateTextFile "text1.txt"
设置文件 = system.GetFile("text1.txt")
设置 newFile = file.OpenAsTextStream(ForWriting, UnicodeFile)
newFile.Write 内容
新文件关闭
希望这种方法能奏效..
您可以使用 iconv。在 Windows 上,您可以在 Cygwin 下使用它。
iconv -f from_encoding -t to_encoding file