【问题标题】:script to save file as unicode将文件保存为 unicode 的脚本
【发布时间】:2010-10-05 22:19:33
【问题描述】:

您知道我可以以编程方式或通过脚本将一组以 ansi 字符编码保存的文本文件转换为 unicode 编码的方法吗?

我想和我用记事本打开文件并选择将其保存为 unicode 文件时一样。

【问题讨论】:

标签: unicode powershell cygwin


【解决方案1】:

这可能对你有用,但请注意它会抓取当前文件夹中的每个文件:


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 是一种“带有可选参数的重定向运算符”。

【讨论】:

  • 使用 out-file 会以某种方式导致一个空文件。我正在使用 PS V5.1
【解决方案2】:

最简单的方法是 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
}

【讨论】:

    【解决方案3】:

    使用 System.IO.StreamReader(读取文件内容)类和 System.Text.Encoding.Encoding(创建进行编码的 Encoder 对象)基类。

    【讨论】:

      【解决方案4】:

      您可以创建一个新的文本文件并将原始文件中的字节写入新文件,在每个原始字节之前放置一个“\0”(假设原始文本文件是英文)。

      【讨论】:

        【解决方案5】:

        您可以使用 iconv。在 Windows 上,您可以在 Cygwin 下使用它。

        iconv -f from_encoding -t to_encoding file
        

        【讨论】:

        • 为什么接受的答案与 Cygwin 相关?该问题被标记为 powershell...
        • 是的,一开始我正在寻找一个 powershell 解决方案,但事实证明这对我来说非常有用,我也可以使用 cygwin。无论如何,所有给出的响应似乎都是有效的方法
        【解决方案6】:

        伪代码...

        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

        希望这种方法能奏效..

        【讨论】:

          猜你喜欢
          • 2013-09-25
          • 1970-01-01
          • 1970-01-01
          • 2016-11-08
          • 2012-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多