2014-10-09 33 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 
相關問題