Convert CRLF Line Endings to LF with PowerShell

Strip Windows carriage returns from scripts and configs copied from Windows to WSL, Linux servers, or Git.

WindowscrlfFilesline-endingsLow risk
Run the one-liner `Get-Content script.sh -Raw | ForEach-Object { $_ -replace "`r`n", "`n" } | Set-Content script.sh -NoNewline` to convert CRLF to LF.

01Command

Command
$ Get-Content script.sh -Raw | ForEach-Object { $_ -replace "`r`n", "`n" } | Set-Content script.sh -NoNewline

02What it does

Windows text files end lines with CRLF (\r\n) while Linux and macOS use LF (\n) — a mismatch that breaks shell scripts with errors like '/bin/bash^M: bad interpreter'. Reading the file with -Raw keeps it as one string, then -replace swaps the two-character sequence for a bare newline. The reverse command restores Windows line endings if a tool needs them.

03Risk

RiskLow risk
RequirementsWindows PowerShell; note that -replace uses regex, so escape backticks exactly as shown.
!Warning: The file is rewritten in place — copy it first if it's large or hard to regenerate.

04Undo

Undo
$ $c = Get-Content script.sh -Raw; $c -replace "`n", "`r`n" | Set-Content script.sh -NoNewline

05Sources

  • Set-Content (Microsoft.PowerShell.Management)
    Microsoft Learn · vendor-doc · 2026-09-17
    Evidence: Documents the -NoNewline parameter so no extra trailing newline is appended when writing the result.
  • about_Special_Characters
    Microsoft Learn · vendor-doc · 2026-09-17
    Evidence: Defines the backtick escape sequences `r (carriage return) and `n (new line) used in the replacement string.

Last verified: 2026-09-19 · Category: Files & Folders

06Related solutions