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), Unix (LF) or Mac (CR)
# Requires PowerShell 3.0 or greater

# 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.

#     ./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 **"

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.

An alternative and much simpler 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 are written these back to a new file, Set-Content will replace 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:

ASCII table
StampMe - Rename a file with the current Date/Time.


© Copyright SS64.com 1999-2014
Some rights reserved