How-to: Change the line endings of a text file [set-eol.ps1]

A PowerShell script to change the line endings of a text file.
This script will work even for a source file that contains a mixture of different file endings.

# set-eol.ps1
# Change the line endings of a text file to: Windows (CR/LF), MacOS/Unix (LF) or Classic Mac (CR)
#
# Requires PowerShell 3.0 or greater:
#Requires –Version 3

# Syntax
#     ./set-eol.ps1 -lineEnding {mac|unix|win} -file FullFilename

#     mac, unix or win  : The file endings desired.
#     FullFilename      : The full pathname of the file to be modified.

#     example:
#     ./set-eol win "c:\demo\data.txt"

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
    [ValidateSet("mac","unix","win")] 
    [string]$lineEnding,
  [Parameter(Mandatory=$True)]
    [string]$file
)

# Convert the friendly name into a PowerShell EOL character
Switch ($lineEnding) {
  "mac"  { $eol="`r" }
  "unix" { $eol="`n" }
  "win"  { $eol="`r`n" }
} 

# Replace CR+LF with LF
$text = [IO.File]::ReadAllText($file) -replace "`r`n", "`n"
[IO.File]::WriteAllText($file, $text)

# Replace CR with LF
$text = [IO.File]::ReadAllText($file) -replace "`r", "`n"
[IO.File]::WriteAllText($file, $text)

#  At this point all line-endings should be LF.

# Replace LF with intended EOL char
if ($eol -ne "`n") {
  $text = [IO.File]::ReadAllText($file) -replace "`n", $eol
  [IO.File]::WriteAllText($file, $text)
}
Echo "   ** Completed **"

For instructions of how to download and run this script see: Run a PowerShell script.

The script loads the whole file into memory so may not be suitable for very large files. The normal PowerShell routine to replace characters is .replace but that will add a trailing CR/LF, so we use ::WriteAllText instead.

A simple but less flexible method from PowerShell.com, is below. Get-Content will identify even non-standard line breaks, so the result is a string array of lines. When these lines are written back into a new file, Set-Content will insert the default Windows CR/LF line endings.

$OldFile = "$home\input.txt"
$NewFile = "$home\output.txt"
Get-Content $OldFile | Set-Content -Path $NewFile

“Well, it’s all right, if you live the life you please, Well, it’s all right, even if the sun don’t shine, Well, it’s all right, we’re going to the end of the line” ~ Traveling Wilburys, End Of The Line

Related PowerShell Cmdlets

ASCII table
StampMe - Rename a file with the current Date/Time.
MacOS: tab2space - Expand tabs and ensure consistent cr/lf line endings.


 
Copyright © 1999-2024 SS64.com
Some rights reserved