【发布时间】:2010-10-05 22:19:33
【问题描述】:
您知道我可以以编程方式或通过脚本将一组以 ansi 字符编码保存的文本文件转换为 unicode 编码的方法吗?
我想和我用记事本打开文件并选择将其保存为 unicode 文件时一样。
【问题讨论】:
标签: unicode powershell cygwin
您知道我可以以编程方式或通过脚本将一组以 ansi 字符编码保存的文本文件转换为 unicode 编码的方法吗?
我想和我用记事本打开文件并选择将其保存为 unicode 文件时一样。
【问题讨论】:
标签: unicode powershell cygwin
这可能对你有用,但请注意它会抓取当前文件夹中的每个文件:
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 'name/of/file'。
Out-File has an -encoding parameter,默认为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”(假设原始文本文件是英文)。
【讨论】:
您可以使用 iconv。在 Windows 上,您可以在 Cygwin 下使用它。
iconv -f from_encoding -t to_encoding file
【讨论】:
伪代码...
Dim 系统、文件、内容、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.Close
system.CreateTextFile "text1.txt"
设置文件 = system.GetFile("text1.txt")
设置 newFile = file.OpenAsTextStream(ForWriting, UnicodeFile)
newFile.Write 内容
newFile.Close
希望这种方法能奏效..
【讨论】: