2

我正在尝试比较两个文件的内容,并判断一个文件的内容是否完全包含在另一个文件中(这意味着如果一个文件有三行,A、B 和 C,我可以按顺序找到这三行吗?第二个文件)。我已经查看diffgrep无法找到相关选项(如果有)。

例子:

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    

任何的想法?

4

4 回答 4

1

假设您file2.txt不包含对正则表达式具有特殊含义的字符,您可以使用:

grep "$(<file2.txt)" file1.txt
于 2013-04-03T10:43:11.007 回答
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

(“exit 0”是为了“可读性”而存在的,所以只有当 fgrep 在 file1.txt 中找不到一行时,人们才能很容易地看到它以 1 退出。不需要)

(fgrep 是文字 grep,搜索字符串(不是正则表达式))

(我没有测试过以上,这是一个普遍的想法。我希望它确实有效^^)

“-x”强制它完全匹配行,即没有附加字符(即:“to”不能再匹配“toto”。添加-x时只有“toto”会匹配“toto”)

于 2013-04-03T10:50:19.243 回答
1

使用这里的答案

使用以下 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
于 2013-04-03T12:04:56.840 回答
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
于 2013-04-03T12:52:02.773 回答