在Linux中並排顯示檔案


簡介

在Linux上處理檔案通常需要同時比較或分析多個檔案。一種有用的方法是在終端並排檢視檔案,以便於比較和分析。在本文中,我們將探討在Linux上並排檢視檔案的各種方法,包括使用diffsdiff命令,以及使用vimemacs文字編輯器。

使用diff命令

diff命令是一個標準的Linux實用程式,用於比較兩個檔案並顯示它們之間的差異。可以使用“-y”或“--side-by-side”標誌將其用於並排檢視檔案。

要使用diff命令,只需輸入命令後跟要比較的兩個檔案的名稱,如下所示:

$ diff file1 file2
4,5c4,5
< This is the fourth line in file
<  This is the fifth line in file
---
> This is the fourth line in filex
> This is the fifth line in filex

要並排檢視檔案,請使用“-y”標誌

輸出將顯示兩個檔案之間的差異,每個檔案的每一行都並排顯示。任何不同的行都將以紅色突出顯示。

以下是如何使用diff命令比較兩個檔案“file1”和“file2”的示例:

$ diff -y  file1 file2
This is the first line in file      This is the first line in file
This is the second line in file     This is the second line in file
This is the third line in file      This is the third line in file
This is the fourth line in file     | This is the fourth line in filex
This is the fifth line in file      | This is the fifth line in filex
This is the sixth line in file      This is the sixth line in file

在這個例子中,我們可以看到兩個檔案的第四行和第五行不同。diff命令以紅色突出顯示了這些差異。

使用sdiff命令

sdiff命令類似於diff命令,但它將兩個檔案之間的差異合併到單個輸出中。要使用sdiff命令,請輸入命令後跟要比較的兩個檔案的名稱,如下所示:

$ sdiff file1 file2

輸出將顯示兩個檔案之間的差異,每個檔案的每一行都並排顯示。任何不同的行都將以紅色突出顯示,並用符號標記它們來自哪個檔案。

以下是如何使用sdiff命令比較兩個檔案file1和file2的示例:

$ sdiff file1 file
This is the first line in file       This is the first line in file
This is the second line in file      This is the second line in file
This is the third line in file       This is the third line in file
This is the fourth line in file      | This is the fourth line in filex
This is the fifth line in file       | This is the fifth line in filex
This is the sixth line in file       This is the sixth line in file

在這個例子中,我們可以看到第四行和第五行在兩個檔案中不同。sdiff命令已將這些差異以紅色突出顯示,並用符號標記它們來自哪個檔案。

使用vim文字編輯器

vim文字編輯器是一個流行且功能強大的工具,用於在Linux上處理檔案。可以使用“-o”或“-O”標誌將其用於並排檢視兩個檔案。要在vim中並排檢視兩個檔案,請輸入命令後跟兩個檔案的名稱,如下所示:

$ vim -o file1 file2

這將在單個視窗中開啟兩個檔案,並且檔案將並排顯示。您可以使用“Ctrl+w”命令在檔案之間導航。以下是如何使用vim在單個視窗中並排檢視兩個檔案file1和file2的示例。

$ vim -O file1 file2

這將在單個視窗中開啟兩個檔案,並且檔案將並排顯示。您可以使用:diffupdate命令檢視兩個檔案之間的差異,該命令將以紅色突出顯示任何差異。

使用emacs文字編輯器

vim一樣,emacs文字編輯器是用於在Linux上處理檔案的強大工具。它還可以使用“-nw”標誌並排檢視兩個檔案。要在emacs中並排檢視兩個檔案,請輸入命令後跟兩個檔案的名稱,如下所示:

$ emacs -nw file1 file2

這將在emacs中單獨的視窗中開啟兩個檔案。您可以使用“Ctrl+x”或“.”在視窗之間導航。以下是如何使用emacs並排顯示兩個檔案“file1”和“file2”的示例

$ emacs -nw file1 file2

這將在emacs中單獨的視窗中開啟兩個檔案。您可以使用M-x ediff命令檢視兩個檔案之間的差異,這將開啟第三個視窗,顯示兩個檔案之間的差異。

結論

在Linux中並排顯示檔案可以成為比較和分析多個檔案的實用工具。sdiff和diff命令以及vim和emacs文字編輯器提供了在終端中並排檢視檔案的方法。無論您需要比較簡單的文字檔案還是更復雜的資料,都有一種方法可以在Linux中並排檢視檔案。

更新於:2023年1月25日

17K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.