Unix newlines to Windows newlines (on Windows)

后端 未结 11 1828
失恋的感觉
失恋的感觉 2020-12-01 05:44

Is there a way (say PowerShell, or a tool) in Windows that can recurse over a directory and convert any Unix files to Windows files.

I\'d be perfectly happy with a wa

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 06:00

    Converting to windows text could be as simple as:

    (get-content file) | set-content file
    

    How about this (with negative lookbehind). Without -nonewline, set-content puts an extra `r`n at the bottom. With the parentheses, you can modify the same file. This should be safe on doing to the same file twice accidentally.

    function unix2dos ($infile, $outfile) {
        (Get-Content -raw $infile) -replace "(?

    The reverse would be this, windows to unix text.

    function dos2unix ($infile, $outfile) {
        (Get-Content -raw $infile) -replace "`r`n","`n" | 
        set-content -nonewline $outfile
    }
    

    Here's another version for use with huge files that can't fit in memory. But the output file has to be different.

    Function Dos2Unix ($infile, $outfile) {
      Get-Content $infile -ReadCount 1000 | % { $_ -replace '$',"`n" } | 
      Set-Content -NoNewline $outfile
    }
    

    Examples (input and output file can be the same):

    dos2unix dos.txt unix.txt
    unix2dos unix.txt dos.txt
    unix2dos file.txt file.txt
    

    If you have emacs, you can check it with esc-x hexl-mode. Notepad won't display unix text correctly; it will all be on the same line. I have to specify the path for set-content, because -replace erases the pspath property.

提交回复
热议问题