PowerShell: Convert File Line Ending
Here's functions to report or convert newline convention.
put this in your PowerShell Profile
function xah-select-line-ending-windows { # .DESCRIPTION # Accept a pipeline from the output of Get-ChildItem. # It output files whose line-ending is Windows CRLF. # .NOTES # Version: 2024-03-12 # .EXAMPLE # dir -file -filter *html | xah-select-line-ending-windows # .LINK # http://xahlee.info/powershell/powershell_fix_newline.html Process { if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; } $content = [IO.File]::ReadAllText($_); if ($content.contains("`r`n")) { $_ } } } function xah-select-line-ending-linux { # .DESCRIPTION # Accept a pipeline from the output of Get-ChildItem. # It output files whose line-ending is Unix or Linux or MacOSX's LF. # .NOTES # Version: 2024-03-12 # .EXAMPLE # dir -file -filter *html | xah-select-line-ending-linux # .LINK # http://xahlee.info/powershell/powershell_fix_newline.html Process { if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; } $content = [IO.File]::ReadAllText($_); if ((-not $content.contains("`r`n")) -and ($content.contains("`n"))) { $_ } } } function xah-select-line-ending-MacOS9 { # .DESCRIPTION # Accept a pipeline from the output of Get-ChildItem. # It output files whose line-ending is MacOS9's CR. # .NOTES # Version: 2024-03-12 # .EXAMPLE # dir -file -filter *html | xah-select-line-ending-MacOS9 # .LINK # http://xahlee.info/powershell/powershell_fix_newline.html Process { if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; } $content = [IO.File]::ReadAllText($_); if ((-not $content.contains("`r`n")) -and ($content.contains("`r"))) { $_ } } } function xah-set-line-ending-linux { # .DESCRIPTION # Accept a pipeline from the output of Get-ChildItem. # Converts line-ending to unix/linux convention of LF. # .EXAMPLE # dir -file -filter *html | xah-set-line-ending-linux # version 2024-03-11 # .LINK # http://xahlee.info/powershell/powershell_fix_newline.html Process { if (-not $MyInvocation.ExpectingInput) { Write-Host "No pipeline received."; return ; } $content = [IO.File]::ReadAllText($_); if ($content.contains("`r`n")) { Copy-Item $_ ($_.fullname + (Get-Date -Format "~yyyyMMddHHmm~")); $newContent = ($content -replace "`r`n", "`n"); [IO.File]::WriteAllText($_, $newContent); } elseif ($content.contains("`r")) { Copy-Item $_ ($_.fullname + (Get-Date -Format "~yyyyMMddHHmm~")); $newContent = ($content -replace "`r", "`n"); [IO.File]::WriteAllText($_, $newContent); } } }
usage:
dir -file -filter *html | xah-select-line-ending-windows | xah-set-line-ending-linux