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

如何比较两个文本文件并输出无关行号的差异内容

实现方案

Linux/macOS 终端命令

使用comm命令可以快速完成需求,自动忽略行顺序和行号:

comm -23 <(sort file1.txt) <(sort file2.txt) > file3.txt

参数说明:

  • -2 隐藏仅存在于第二个文件的行
  • -3 隐藏两个文件共有的行
  • 最终仅输出仅存在于第一个文件的行,<(sort 文件名) 是进程替换语法,无需生成临时排序文件即可直接传入排序后的内容。

Windows PowerShell 命令

Compare-Object (Get-Content file1.txt) (Get-Content file2.txt) | Where-Object {$_.SideIndicator -eq '<='} | Select-Object -ExpandProperty InputObject | Out-File file3.txt -Encoding UTF8

说明:SideIndicator = '<=' 代表筛选仅在第一个文件中存在的内容,指定UTF8编码避免特殊字符乱码。

跨平台Python实现

如果需要保留第一个文件的原始行顺序,或者需要跨系统运行,可以使用以下Python代码:

# 读取文件内容
with open("file1.txt", "r", encoding="utf-8") as f:
    file1_lines = f.read().splitlines()
with open("file2.txt", "r", encoding="utf-8") as f:
    file2_lines = set(f.read().splitlines())

# 筛选仅在第一个文件中存在的行,保留原始顺序
res = [line for line in file1_lines if line not in file2_lines]

# 写入结果文件
with open("file3.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(res) + "\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:06:09