Bash:判断文件是否包含在另一个文件中

时间:2013-04-03 10:36:47

标签: bash diff file-comparison

我正在尝试比较两个文件的内容,并判断一个文件的内容是否完全包含在另一个文件中(意味着如果一个文件有三行,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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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中找不到行时,才能很容易地看到它以1退出。这不是必需的)

(fgrep是一个升级的grep,搜索字符串(不是正则表达式))

(我没有测试过上面的内容,这是一个大致的想法。我希望它确实有用^^)

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

答案 2 :(得分: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

答案 3 :(得分:0)

如果这个awk“one-liner”^ _ ^适用于您的真实文件,请尝试。对于你问题中的示例文件,它有效:

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