2009-02-06 36 views
5

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

我想做的和我一样,当我用记事本打开文件,并选择将它保存为一个Unicode文件。

+0

重复的http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets,也见http://stackoverflow.com/questions/76482/powershell -setting-encoding-for-get-content-pipeline – 2009-02-07 11:13:48

回答

-1

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

iconv -f from_encoding -t to_encoding file 
+3

为什么接受的答案与Cygwin有关?这个问题被标记为powershell ... – guillermooo 2009-02-09 11:51:47

0

使用System.IO.StreamReader(读取文件内容)类与System.Text.Encoding.Encoding(创建编码器的编码对象)基类一起使用。

-1

伪代码...

昏暗系统,文件,内容,NEWFILE,的oldfile

CONST ForReading的= 1,ForWriting = 2,ForAppending = 3 CONST AnsiFile = -2,UnicodeFile = -1

设置系统=的CreateObject( “Scripting.FileSystemObject的...

设置文件= system.GetFile(” text1.txt“)

设置的oldfile = file.OpenAsTextStream(ForReading的,AnsiFile)

内容= oldFile.ReadAll()

oldFile.Close

system.CreateTextFile “text1.txt”

集文件系统= .GetFile( “text1.txt”)

集NEWFILE = file.OpenAsTextStream(ForWriting,UnicodeFile)

newFile.Write内容

newFile.Close

希望这种做法将工作..

3

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

您可以创建一个新的文本文件,并写入从原始文件到新的一个字节,放置一个“\每个原始字节之前的'0'(假定原始文本文件是英文的)。

10

这可能为你工作,但是请注意,它会抓住每文件在当前文件夹:


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") } 

史蒂芬穆拉夫斯基建议改为使用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是一个“重定向操作员optiona l参数“的种类。

相关问题