Find/replace string with carriage return and line feed in PowerShell

Jerry Sweeton picture Jerry Sweeton · Mar 8, 2013 · Viewed 23k times · Source

Is there a way to have PowerShell find and replace a string (for example ~}}|{{E) with a carriage return and line feed (\r\nE)?

For example:

$filenames = @("E:\blergfest.csv")
foreach ($file in $filenames) {
    $outfile = "$file" + ".out"

    Get-Content $file | Foreach-object {
        $_ -replace '\~}}|{{E', '\r\nE' `
            -replace '\|\r\n', '\r\n'
    } | Set-Content $outfile
}

Answer

zdan picture zdan · Mar 8, 2013

To create a string that contains the control characters with carriage return and line feed, you would use double quotes and use the backtick character ` which is the powershell escape code. Like this:

"`r`nE"