File-Comparison

比較兩個文件並輸出匹配

  • July 6, 2017

我有類似的文件:

文件1:

1.1.1.7 mounting of udf filesystems is disabled Fail
1.1.1.8 mounting of FAT filesystems is disabled  Fail
1.1.5 noexec option set on /tmp partition   Fail
1.1.17 noexec option set on /dev/shm partition  Fail
1.1.21 sticky bit is set on all world-writable directories  Fail
1.3.1 AIDE is installed Fail

文件2:

1.1.1.7 Ensure mounting of udf filesystems is disabled
1.1.1.8 Ensure mounting of FAT filesystems is disabled
1.1.3 Ensure nodev option set on /tmp partition
1.1.4 Ensure nosuid option set on /tmp partition

我想比較第一列上的兩個文件並輸出它們匹配的位置。對於上面的內容,輸出將是:

1.1.1.7 Ensure mounting of udf filesystems is disabled
1.1.1.7 mounting of udf filesystems is disabled Fail
1.1.1.8 Ensure mounting of FAT filesystems is disabled
1.1.1.8 mounting of FAT filesystems is disabled  Fail

我該怎麼做?

另外我將如何扭轉它,以便我可以顯示那些不匹配的?將 File1 與 File2 進行比較,反之亦然?

awk '
 NR == FNR {a[$1] = $0; next} 
 ($1 in a) {print; print a[$1]}
' File1 File2
1.1.1.7 Ensure mounting of udf filesystems is disabled
1.1.1.7 mounting of udf filesystems is disabled Fail
1.1.1.8 Ensure mounting of FAT filesystems is disabled
1.1.1.8 mounting of FAT filesystems is disabled  Fail

如果您想對 File2 中的不匹配條目進行簡單測試

awk 'NR==FNR {a[$1]=$0; next} !($1 in a)' File1 File2
1.1.3 Ensure nodev option set on /tmp partition
1.1.4 Ensure nosuid option set on /tmp partition

相反,File1 中的條目不匹配

awk 'NR==FNR {a[$1]=$0; next} !($1 in a)' File2 File1
1.1.5 noexec option set on /tmp partition   Fail
1.1.17 noexec option set on /dev/shm partition  Fail
1.1.21 sticky bit is set on all world-writable directories  Fail
1.3.1 AIDE is installed Fail

(這print是隱含的)。

引用自:https://unix.stackexchange.com/questions/375742