Unix newlines to Windows newlines (on Windows)

后端 未结 11 1750
失恋的感觉
失恋的感觉 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

    There is dos2unix and unix2dos in Cygwin.

    0 讨论(0)
  • 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 "(?<!`r)`n","`r`n" | 
        set-content -nonewline $outfile
    }
    

    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.

    0 讨论(0)
  • 2020-12-01 06:02

    If Cygwin isn't for you, there are numerous standalone executables for unix2dos under Windows if you Google around, or you could write one yourself, see my similar (opposite direction for conversion) question here.

    0 讨论(0)
  • 2020-12-01 06:08

    Opening a file with Unix line endings in Wordpad and saving it will rewrite all the line endings as DOS. A bit laborious for large numbers of files, but it works well enough for a few files every once in a while.

    0 讨论(0)
  • 2020-12-01 06:11

    download vim, open your file and issue

    :se fileformat=dos|up
    

    Batch for multiple files (all *.txt files in C:\tmp - recursive):

    :args C:\tmp\**\*.txt
    :argdo se fileformat=dos|up
    
    0 讨论(0)
提交回复
热议问题