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

批量处理文本文件:移除换行符但保留票号开头行的换行

批量整理文本:保留票号开头的行,合并其余换行

你需要实现的是将所有非6位数字票号开头的行的换行符替换为空格,最终每行都以这类票号开头。以下是几种高效的自动化处理方案:

方案1:使用sed命令(Linux/macOS/Git Bash)

直接执行命令即可处理大文件,无需打开编辑器:

sed -E ':a; N; /\n[0-9]{6}/!s/\n/ /; ta' input.txt > output.txt

逻辑说明

循环读取内容,把换行后不是6位数字开头的部分,将换行符替换为空格;遇到以6位数字开头的行时,保留换行作为分隔。

方案2:Python脚本(跨平台,适合超大文件)

如果需要更灵活的处理(比如跳过空行、自定义票号长度),可以用Python脚本:

output = []
current_entry = ""

with open("input.txt", "r", encoding="utf-8") as f:
    for line in f:
        line_clean = line.strip()
        if not line_clean:
            continue  # 跳过空行
        
        # 判断是否以6位数字票号开头
        if len(line_clean) >=6 and line_clean[:6].isdigit():
            if current_entry:
                output.append(current_entry)
            current_entry = line_clean
        else:
            if current_entry:
                current_entry += " " + line_clean
            else:
                current_entry = line_clean

# 写入最后一条记录
if current_entry:
    output.append(current_entry)

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(output) + "\n")

使用方法

  1. 将脚本保存为merge_lines.py
  2. 把要处理的文件命名为input.txt放在同一目录
  3. 执行python merge_lines.py,结果会生成在output.txt

方案3:Notepad++图形界面操作

如果你习惯用编辑器处理:

  1. 打开目标文件,按Ctrl+H打开替换窗口
  2. 切换到正则表达式模式,勾选「匹配换行符」
  3. 查找内容:\r\n(?!\d{6})(如果是Linux/macOS文件,换成\n(?!\d{6}))
  4. 替换为: (一个空格)
  5. 点击「全部替换」即可完成处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:10:28