You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查代码是否使用\r或\r\n并替换为另一种换行符

换行符替换操作方法

一、编辑器内批量替换

VS Code

  • 打开目标文件,按下Ctrl+H(Windows/Linux)或Cmd+H(Mac)打开替换面板
  • 点击面板右上角的「.*」按钮开启正则表达式模式
  • 查找框输入\r\n(或\r,根据你要替换的目标换行符选择),替换框输入\n(或\r,按需切换)
  • 点击「替换全部」完成批量替换

Sublime Text

  • 按下Ctrl+H(Windows/Linux)或Cmd+H(Mac)打开替换面板
  • 点击面板左下角的「.*」启用正则匹配
  • 查找内容填\r\n(或\r),替换内容填\n(或\r)
  • 点击「Replace All」完成替换

二、命令行批量处理(多文件场景适用)

Linux/macOS(sed命令)

  • 替换目录下所有.txt文件的\r\n为\n:
    sed -i 's/\r$//' *.txt
    
  • 替换单个文件的\n为\r\n:
    sed -i 's/$/\r/' example.txt
    

Windows(PowerShell命令)

  • 替换单个文件的\r\n为\n:
    (Get-Content example.txt -Raw) -replace "`r`n", "`n" | Set-Content example.txt -NoNewline
    
  • 替换单个文件的\n为\r\n:
    (Get-Content example.txt -Raw) -replace "`n", "`r`n" | Set-Content example.txt -NoNewline
    

三、代码内动态替换(以Python为例)

  • 读取文件时统一换行符:
    with open("example.txt", "r", newline="") as f:
        content = f.read()
    # 统一替换为\n
    content = content.replace("\r\n", "\n").replace("\r", "\n")
    with open("example.txt", "w", newline="\n") as f:
        f.write(content)
    

内容的提问来源于stack exchange,提问作者ellgee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:52:10