如何使用diff命令提取file2中相对于file1的新增行?
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': Tellsdiffto print any line that's only present in file2 exactly as it appears (%Lrepresents 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

