2009-02-06 71 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參數「的種類。

相關問題