Linux

Linux 比較兩個相似檔案的內容差異教學與範例

介紹如何在 Linux 中使用 prdiffpastecolumn 指令,顯示與比較兩個相似檔案的內容差異。

兩個相似檔案

假設我們有 file1.txtfile2.txt 兩個內容很相似的檔案,想要比較其中的差異:

# 查看 file1.txt 檔案內容
cat file1.txt
acpi
adduser.conf
alsa
alternatives
anacrontab
apache2
apg.conf
apm
apparmor
# 查看 file2.txt 檔案內容
cat file2.txt
acpi
adduser
alsa
alternatives
anacrontab
apg.conf
apm
apparmor
apparmor.d

如果只用 cat 輸出內容,很難一眼看出兩個檔案的差異在哪裡。

diff 指令

diff 是專門用來比較檔案差異的工具,搭配 -y--side-by-side 參數可以將兩個檔案以左右並排的方式呈現,方便查看差異的地方:

# 左右並排,比較差異
diff -y file1.txt file2.txt
acpi								acpi
adduser.conf						      |	adduser
alsa								alsa
alternatives							alternatives
anacrontab							anacrontab
apache2							      <
apg.conf							apg.conf
apm								apm
apparmor							apparmor
							      >	apparmor.d

在這個輸出中,大於(>)與小於(<)的符號代表新增與移除的行,而 | 符號則是代表有修改過的行。

如果感覺輸出的板面太寬或是太窄,可以使用 -W--width 參數來調整版面寬度:

# 設定輸出版面寬度為 40
diff -W 40 -y file1.txt file2.txt
acpi			acpi
adduser.conf	   |	adduser
alsa			alsa
alternatives		alternatives
anacrontab		anacrontab
apache2		   <
apg.conf		apg.conf
apm			apm
apparmor		apparmor
		   >	apparmor.d

sdiff 指令

sdiff 指令就相當於 diff 加上 -y 參數,也可以輸出左右並排的差異內容:

# 左右並排,比較差異
sdiff file1.txt file2.txt
acpi								acpi
adduser.conf						      |	adduser
alsa								alsa
alternatives							alternatives
anacrontab							anacrontab
apache2							      <
apg.conf							apg.conf
apm								apm
apparmor							apparmor
							      >	apparmor.d

若要調整輸出版面寬度,則可使用 -w--width 參數:

# 設定輸出版面寬度為 40
sdiff -w 40 file1.txt file2.txt
acpi			acpi
adduser.conf	   |	adduser
alsa			alsa
alternatives		alternatives
anacrontab		anacrontab
apache2		   <
apg.conf		apg.conf
apm			apm
apparmor		apparmor
		   >	apparmor.d

colordiff 指令

colordiff 指令是 diff 的彩色版本,使用的方式跟 diff 相同:

# 彩色排版,左右並排,比較差異
colordiff -W 40 -y file1.txt file2.txt
colordiff 彩色排版,左右並排,比較差異

vimdiffgvimdiff 指令

若習慣使用 Vim 編輯器的人,可以使用 vimdiff 來查看兩個檔案的差異:

# 左右並排,比較差異
vimdiff file1.txt file2.txt
vimdiff 左右並排,比較差異

或是使用 GVim 附帶的 gvimdiff 也可以:

# 左右並排,比較差異
gvimdiff file1.txt file2.txt
gvimdiff 左右並排,比較差異

pastecolumn 指令

如果只是要單純將兩個檔案的每一行串接在一起,合併輸出,可以使用 paste 指令,而為了使輸出的資料更容易閱讀,可以再搭配 column 將資料轉為對齊的表格:

# 合併 file1.txt 與 file2.txt,並以表格方式輸出
paste file1.txt file2.txt | column -t -s $'\t'
acpi          acpi
adduser.conf  adduser
alsa          alsa
alternatives  alternatives
anacrontab    anacrontab
apache2       apg.conf
apg.conf      apm
apm           apparmor
apparmor      apparmor.d

參考資料

Share
Published by
Office Guide
Tags: Bash

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

11 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago