2013-04-03 78 views
2

我試圖比較兩個文件的內容並判斷一個文件的內容是否完全包含在另一個文件中(意思是說如果一個文件有三行A,B和C ,我可以在第二個文件中按順序找到這三行)。我查看了diffgrep,但無法找到相關選項(如果有)。Bash:判斷一個文件是否包含在另一個文件中

例子:

file1.txt file2.txt <= should return true (file2 is included in file1) 
--------- --------- 
abc   def 
def   ghi 
ghi 
jkl  

file1.txt file2.txt <= should return false (file2 is not included in file1) 
--------- --------- 
abc   abc 
def   ghi 
ghi 
jkl  

任何想法?

+0

'join(1)'可能很有用。 http://linux.die.net/man/1/join – NPE

+0

可能f1和f2有空行嗎? – Kent

+0

是的,他們可以。 – gregseth

回答

1

here

使用答案使用下面的Python函數:

def sublistExists(list1, list2): 
    return ''.join(map(str, list2)) in ''.join(map(str, list1)) 

在行動:

In [35]: a=[i.strip() for i in open("f1")] 
In [36]: b=[i.strip() for i in open("f2")] 
In [37]: c=[i.strip() for i in open("f3")] 

In [38]: a 
Out[38]: ['abc', 'def', 'ghi', 'jkl'] 

In [39]: b 
Out[39]: ['def', 'ghi'] 

In [40]: c 
Out[40]: ['abc', 'ghi'] 

In [41]: sublistExists(a, b) 
Out[41]: True 

In [42]: sublistExists(a, c) 
Out[42]: False 
1

假設你file2.txt不包含對正則表達式的特殊含義的字符,你可以使用:

grep "$(<file2.txt)" file1.txt 
+0

用這個命令,file2有多大? – Kent

+1

如果在我的第二個示例中存在部分匹配,則它不起作用(即使使用'grep -F') – gregseth

1

這應該工作,即使你的FILE2.TXT包含特殊字符:

cp file1.txt file_read.txt 

while read -r a_line ; do 
    first_line_found=$(fgrep -nx "${a_line}" file_read.txt 2>/dev/null | head -1) 
    if [ -z "$first_line_found" ]; 
    then 
     exit 1 # we couldn't find a_line in the file_read.txt 
    else 
     { echo "1,${first_line_found}d" ; echo "w" ; } | ed file_read.txt #we delete up to line_found 
    fi 
done < file2.txt 
exit 0 

( 「退出0」是爲了「可讀性」,所以人們可以很容易地看到它只有在fgrep無法在file1.txt中找到一行時纔會退出,不需要)

(fgrep是一個整數grep,尋找一個字符串(不是正則表達式))

(我還沒有測試過上面的,這是一個普遍的想法。我希望它能夠正常工作^^)

「-x」迫使它完全匹配行,即沒有其他字符(即:「to」不能再匹配「toto」。只有「toto」匹配「TOTO」,並稱當-x)

+0

'grep -Fx'解決了正則表達式和部分行匹配的問題。其餘的工作。 – gregseth

+0

我知道我看了fgrep(= grep -F)的手冊頁,並在你的評論前編輯它^^但是,謝謝! –

+1

我不確定它是如何工作的,雖然... grep部分檢查線是否匹配,循環部分是爲每一行執行的,但是如何保存順序? – gregseth

0

請嘗試,如果這awk「單行」^ _ ^爲您的真實文件工作。對於您的問題中的示例文件,它的工作原理如下:

awk 'FNR==NR{a=a $0;next}{b=b $0} 
END{while(match(b,a,m)){ 
    if(m[0]==a) {print "included";exit} 
    b=substr(b,RSTART+RLENGTH) 
    } 
    print "not included" 
}' file2 file1 
相關問題