2011-02-24 3 views
7

Powershell에서 유닉스 파일 형식은 어떻게 만듭니 까? 나는 다음을 사용하여 파일을 만들지 만 항상 윈도우 형식으로 파일을 만듭니다. 내가 알고있는 것처럼Powershell을 사용하는 UNIX 형식 파일

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

, 새로운 라인 문자는 유닉스 형식이 줄의 끝에 만 LF를 필요로하는 반면 그것은 Windows 형식의 파일이 될 수 있도록 CRLF. 나는 다음과 CRLF를 교체 시도했지만 작동하지 않았다

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

에는 CRLF가 없기 때문에 귀하의 테스트가 작동하지 않습니다에 "Hello World" – x0n

+0

x0n @ 파일에 쓸 때, cr/lf는 내가하려고했던 지점 인 – aldrin

+0

에 추가됩니다. 분명히 바꾸기 작업은 쓰기 (out-file) 이전이므로 out-file이 CRLF를 추가하면 바꾸려고 시도한 후에 발생합니다. – x0n

답변

5

하나 추한 보이는 대답은 (unix.txt로 출력 dos.txt 입력을 복용)한다 :

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

하지만, Set-Content가 자체적으로이 작업을 수행 할 수있게하려면이 솔루션은 스트리밍되지 않으므로 대용량 파일에서 제대로 작동하지 않습니다.

그리고이 솔루션은 파일을 DOS 라인 끝으로 종료합니다 뿐만 아니라 ... 그래서 그것은 100 %가 아닙니다

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

위에 게시, 어떤 경우에는 convertions를 인코딩 실패 :
+5

솔루션을 확장하면 실제로 바이트를 쓰고 DOS 줄 끝을 피할 수 있습니다. sc unix.txt ([byte [] [char []] "$ contenttext") -Encoding Byte – aldrin

+0

좋은 생각, 고맙습니다. 그에 대한! –

+3

(gc dos.txt) -join "'n"> unix.txt – x0n

9

2

은 내가 솔루션 것으로 나타났습니다를 ConvertTo-UnixLineEnding라는 PowerShell Community Extensions에서 cmdlet에 있습니다.

그래서, 여기에 다른 해결책 아직 (좀 더 자세한 정보는, 그러나 바이트와 직접 작동) :

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