2011-02-24 40 views
7

如何在Powershell中創建unix文件格式?我正在使用以下來創建一個文件,但它始終以windows格式創建它。帶有Powershell的UNIX格式文件

"hello world" | out-file -filepath test.txt -append 

據我所知,新的行字符CRLF使它成爲一個Windows格式文件,而unix格式只需要在行尾有一個LF。我試着用下面的替換CRLF,但沒有奏效

"hello world" | %{ $_.Replace("`r`n","`n") } | out-file -filepath test.txt -append 
+0

您的測試不工作,因爲在沒有CRLF的「Hello World」 – x0n 2011-02-24 21:50:24

+0

@ x0n當你將它寫出到一個文件中時,那麼cr/lf被附加到 – aldrin 2011-02-25 08:34:00

+0

這一行,這正是我試圖創建的點。顯然你的替換操作是在寫入之前(out-file),所以如果out-file添加了CRLF,它會在你試圖替換它之後發生。 – x0n 2011-02-25 16:58:04

回答

5

一個面目可憎的答案是(以輸入從dos.txt輸出到unix.txt):

[string]::Join("`n", (gc dos.txt)) | sc unix.txt 

但我真的希望能夠使Set-Content自己做到這一點,並且此解決方案不會流式傳輸,因此在大型文件上無法正常工作......

而且此解決方案將以DOS行結束文件結束以及...所以它不是100%

+5

擴展你的解決方案,實際上有一種方法來寫字節並避免DOS行結束:sc unix.txt([byte []] [char []]「$ contenttext」) - 編碼字節 – aldrin 2011-02-24 11:26:14

+0

好的思考,thanx爲了那個原因! – 2011-02-24 11:34:32

+3

(gc dos.txt)-join「'n」> unix.txt – x0n 2011-02-24 21:52:20

2

我發現,解決辦法:

sc unix.txt ([byte[]][char[]] "$contenttext") -Encoding Byte 

上面貼失敗在某些情況下,編碼convertions。

所以,這裏又是另一種解決方案(有點冗長,但它與字節直接作用):

function ConvertTo-LinuxLineEndings($path) { 
    $oldBytes = [io.file]::ReadAllBytes($path) 
    if (!$oldBytes.Length) { 
     return; 
    } 
    [byte[]]$newBytes = @() 
    [byte[]]::Resize([ref]$newBytes, $oldBytes.Length) 
    $newLength = 0 
    for ($i = 0; $i -lt $oldBytes.Length - 1; $i++) { 
     if (($oldBytes[$i] -eq [byte][char]"`r") -and ($oldBytes[$i + 1] -eq [byte][char]"`n")) { 
      continue; 
     } 
     $newBytes[$newLength++] = $oldBytes[$i] 
    } 
    $newBytes[$newLength++] = $oldBytes[$oldBytes.Length - 1] 
    [byte[]]::Resize([ref]$newBytes, $newLength) 
    [io.file]::WriteAllBytes($path, $newBytes) 
}