用 PowerShell 把 CRLF 换行符转成 LF
把从 Windows 复制到 WSL、Linux 服务器或 Git 的脚本换行符统一为 LF,避免报错。
运行 `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 -NoNewline02作用说明
Windows 文本文件以 CRLF(\r\n)结尾,而 Linux 和 macOS 用 LF(\n),混用会导致 shell 脚本报 /bin/bash^M: bad interpreter 之类的错误。先用 -Raw 把整个文件读成一个字符串,再用 -replace 把两个字符的换行序列替换为单个换行。反向命令则可以把 LF 恢复成 Windows 的 CRLF。
03风险
!注意: 命令会直接重写原文件,文件较大或重要时请先备份。
04撤销
撤销
$ $c = Get-Content script.sh -Raw; $c -replace "`n", "`r`n" | Set-Content script.sh -NoNewline05来源
- Set-Content (Microsoft.PowerShell.Management)依据: Documents the -NoNewline parameter so no extra trailing newline is appended when writing the result.
- about_Special_Characters依据: Defines the backtick escape sequences `r (carriage return) and `n (new line) used in the replacement string.
最后验证: 2026-09-19 · 分类: 文件与文件夹