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

如何使用diff命令提取file2中相对于file1的新增行?

Extracting Only New Lines from file2 Using diff

Hey there! I totally get why you might have missed this in the man page—some of diff's more niche options are easy to overlook. But there are actually a couple of straightforward ways to get exactly what you want: only the lines that are unique to file2.

Method 1: Use diff's Custom Format Options

The most direct way is to leverage diff's formatting flags to suppress lines from file1 and unchanged lines, while keeping only the new lines from file2:

diff --new-line-format='%L' --old-line-format='' --unchanged-line-format='' file1 file2

Let's break down what each part does:

  • --new-line-format='%L': Tells diff to print any line that's only present in file2 exactly as it appears (%L represents the line content).
  • --old-line-format='': Suppresses any lines that are only in file1 (we don't care about those here).
  • --unchanged-line-format='': Suppresses lines that exist in both files (since we only want the new ones).

Running this command with your files will output:

/root/new
/root/new_new

Method 2: Unified Diff + Grep (Simpler to Remember)

If the format flags feel too verbose, you can use the unified diff format and filter the output with grep:

diff -u file1 file2 | grep '^+' | grep -v '^+++'

Here's the breakdown:

  • diff -u: Generates a unified diff where lines starting with + are new additions in file2.
  • grep '^+': Filters to keep only lines that start with + (the new lines).
  • grep -v '^+++': Excludes the header line that starts with +++ (which just lists the filename of file2).

This will also give you the exact output you're expecting.

Note for Unsorted Files

If your files aren't sorted, diff might not correctly identify matching lines (since it compares line order). To fix this, sort both files on the fly using process substitution:

For Method 1:

diff --new-line-format='%L' --old-line-format='' --unchanged-line-format='' <(sort file1) <(sort file2)

For Method 2:

diff -u <(sort file1) <(sort file2) | grep '^+' | grep -v '^+++'

Either approach will work perfectly for your use case!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:56:53