继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Linux下文件对比(diff/comm/egrep)

ABOUTYOU
关注TA
已关注
手记 300
粉丝 67
获赞 358

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 -f

egrep -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

diff

diff 相对更复杂些,可以比较两个文件,或者文件和文件夹,或者文件夹和文件夹
这里着重于说明两个文件的相同部分,和不同部分的统计。

对于diff命令来说,需要明白"|" 表示对应的行不同(使用-y参数时有'|',表示并且显示),">" 表示行只存在于后面的文件,"<" 表示行只存在前面的文件

## 得到两个文件相同部分diff -y file1 file2 | egrep -v '<|>|\|' | awk '{print $1}'
## 例子如下
root@pts/1 $ diff -y file1 file2|egrep -v '<|>|\|'|awk '{print $1}'a
b
c
d
e## 得到只存于第一个文件diff file1 file2 |grep  '<'|awk '{print $2}'## 例子如下root@pts/1 $ diff file1 file2 |grep  '<'|awk '{print $2}'f
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

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP