title: Linux下文件對比(diff/comm/egrep)
date: 2016-06-03
comments: true
category: Linux
tags: linux, difff, comm, egrep/grep
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:13
root@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