2014-10-09 63 views
0

我需要通过两个不同的文件获得差异和uniq输出。如何在不同和uniq中找到两个文件内容

此时就把one.txt存盘

The lightning and thunder 
They go and come; 
But the stars and the stillness 
Are always at home. 

two.txt

The lightning and thunder 
They go and come; 
Tyger! Tyger! burning bright 
In the forests of the night, 
What immortal hand or eye 
But the stars and the stillness 
Are always at home. 

我想在这样两种不同的方式来获得输出。

same.txt

The lightning and thunder 
They go and come; 
But the stars and the stillness 
Are always at home. 

diff.txt

Tyger! Tyger! burning bright 
In the forests of the night, 
What immortal hand or eye 
But the stars and the stillness 
+0

使用'diff文件file2' – 2014-10-09 12:36:09

+2

行 “但是明星与寂静” 不应该在'diff.txt' 。 – fedorqui 2014-10-09 12:44:00

回答

2

假设你的文件one.txt包含two.txt,您可以同时使用grep-f这一点。然后,-v反转输出。

什么匹配:

grep -f f1 f2 > same.txt 

见输出:

$ cat same.txt 
The lightning and thunder 
They go and come; 
But the stars and the stillness 
Are always at home. 

什么不同:

grep -vf f1 f2 > diff.txt 

见输出:

$ cat diff.txt 
Tyger! Tyger! burning bright 
In the forests of the night, 
What immortal hand or eye 

man grep

-f FILE,--file = FILE

从文件中获取模式,每行一个。空文件包含零个 模式,因此不匹配任何内容。 (-f通过 POSIX指定。)

-v,--invert匹配

反相的匹配感,以选择不匹配的行。 (-v是POSIX指定 。)

+0

这只适用于因为f2包含f1 – 2014-10-09 12:37:06

+0

真,@RaulAndres。就像OP一样,我只是更新了它。 – fedorqui 2014-10-09 12:40:02

0

对于巧合:

grep -f one.txt two.txt > same.txt 

对于diffeerences:

cat one.txt two.txt| grep -f same.txt 
0

如果文本的顺序并不重要。你可以排序和做一个通信。

排序和存储

sort one.txt > one_sorted.txt 
sort two.txt > two_sorted.txt 

之后做通讯

comm -3 one_sorted.txt two_sorted.txt > diff.txt 
comm -12 one_sorted.txt two_sorted.txt > same.txt