Linux下文件对比(diff/comm/egrep)
comm需要注意 `comm` 比较的时候文件是要求排序过的不加参数的时候结果分“三行”显示,第一行是两个文件相同部分,第二行只存在于是“第一个”文件中的内容,第三行是只存在于“第二个”文件中的内容root@pts/1 $ cat file1
a
b
c
d
e
f
g
root@pts/1 $ cat file2
a
b
c
d
e
h
i
j
root@pts/1 $ comm file1 file2
a
b
c
d
e
f
g
h
i
j带参数:
-1 不显示只在第1个文件里出现过的列。
-2 不显示只在第2个文件里出现过的列。
-3 不显示同时在第1和第2个文件里出现过的列。root@pts/1 $ comm -1 file1 file2
a
b
c
d
e
h
i
j
newData [/tmp/data] 2016-06-03 15:33:08
root@pts/1 $ comm -2 file1 file2
a
b
c
d
e
f
g
newData [/tmp/data] 2016-06-03 15:33:13root@pts/1 $ comm -3 file1 file2
f
g
h
i
j同理 -1/-2/-3 可以组合使用
comm -12 得到两个文件相同部分
comm -13 得到只存在第二个文件中的部分
comm -23 得到只存在第一个文件中的部分root@pts/1 $ comm -13 file1 file2
h
i
j
root@pts/1 $ comm -23 file1 file2
f
g
root@pts/1 $ comm -12 file1 file2
a
b
c
d
e
egrep -fegrep -f 相对来说更简单明了些
egrep -f file1 file2 相当于 comm -12 file1 file2得到相同部分root@pts/1 $ egrep -f file1 file2
a
b
c
d
egrep -f file1 -v file2 相当于 comm -13 file1 file2 得到只存在于第二个文件中的部分root@pts/1 $ egrep -f file1 -v file2
h
i
j
egrep -f file2 -v file1 相当于 comm -23 file1 file2 得到只存在于第一个文件中的部分root@pts/1 $ egrep -f file2 -v file1
f
g
diffdiff 相对更复杂些,可以比较两个文件,或者文件和文件夹,或者文件夹和文件夹
这里着重于说明两个文件的相同部分,和不同部分的统计。
对于diff命令来说,需要明白"|" 表示对应的行不同(使用-y参数时有'|',表示并且显示),">" 表示行只存在于后面的文件,"|\|' | awk '{print $1}'
## 例子如下
root@pts/1 $ diff -y file1 file2|egrep -v '|\|'|awk '{print $1}'a
b
c
d
e## 得到只存于第一个文件diff file1 file2 |grep '
g## 得到只存于第二个文件diff file1 file2 |grep '>'|awk '{print $2}'## 例子如下root@pts/1 $ diff file1 file2 |grep '>'|awk '{print $2}'h
i
j
作者:全栈运维
链接:https://www.jianshu.com/p/058a025c9b1d