用 PowerShell 把 CRLF 换行符转成 LF

把从 Windows 复制到 WSL、Linux 服务器或 Git 的脚本换行符统一为 LF,避免报错。

Windows换行符文件换行符低风险
运行 `Get-Content script.sh -Raw | ForEach-Object { $_ -replace "`r`n", "`n" } | Set-Content script.sh -NoNewline`,即可把 CRLF 转成 LF。

01命令

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

02作用说明

Windows 文本文件以 CRLF(\r\n)结尾,而 Linux 和 macOS 用 LF(\n),混用会导致 shell 脚本报 /bin/bash^M: bad interpreter 之类的错误。先用 -Raw 把整个文件读成一个字符串,再用 -replace 把两个字符的换行序列替换为单个换行。反向命令则可以把 LF 恢复成 Windows 的 CRLF。

03风险

风险低风险
使用条件Windows PowerShell; note that -replace uses regex, so escape backticks exactly as shown.
!注意: 命令会直接重写原文件,文件较大或重要时请先备份。

04撤销

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

05来源

  • Set-Content (Microsoft.PowerShell.Management)
    Microsoft Learn · vendor-doc · 2026-09-17
    依据: 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
    依据: Defines the backtick escape sequences `r (carriage return) and `n (new line) used in the replacement string.

最后验证: 2026-09-19 · 分类: 文件与文件夹

06相关方案