用于将文件另存为unicode的脚本

riv*_*er0 6 unicode powershell cygwin

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

当我用记事本打开文件并选择将其保存为unicode文件时,我想做同样的事情.

gui*_*ooo 11

这可能适合您,但请注意它将获取当前文件夹中的每个文件:


Get-ChildItem | Foreach-Object { $c = (Get-Content $_); `
Set-Content -Encoding UTF8 $c -Path ($_.name + "u") }
Run Code Online (Sandbox Code Playgroud)

使用别名的简洁方法相同:


gci | %{ $c = (gc $_); sc -Encoding UTF8 $c -Path ($_.name + "u") }
Run Code Online (Sandbox Code Playgroud)

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

Run Code Online (Sandbox Code Playgroud)

PS> [system.string] | Set-Content test.txt
PS> Get-Content test.txt

System.String

# test.txt encoding is "ANSI" (Windows character set)
Run Code Online (Sandbox Code Playgroud)

实际上,如果您不需要任何特定的Unicode编码,您还可以执行以下操作将文本文件转换为Unicode:


PS> Get-Content sourceASCII.txt > targetUnicode.txt
Run Code Online (Sandbox Code Playgroud)

Out-File 是一种"可选参数的重定向运算符".


jfs*_*tos -1

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

iconv -f from_encoding -t to_encoding file
Run Code Online (Sandbox Code Playgroud)

  • 为什么接受的答案与 Cygwin 有关?该问题被标记为 powershell... (4认同)