Converting to Windows text could be as simple as:
(Get-Content file) | Set-Content file
Use the following (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.