在 Linux 中并排显示文件

linuxoperating systemopen source更新于 2026/1/25 8:07:17

简介

在 Linux 上处理文件通常需要同时比较或分析多个文件。一个实用的方法是在终端中并排查看文件,以便于比较和分析。在本文中,我们将探讨在 Linux 上并排查看文件的各种方法,包括使用 diff 和 sdiff 命令,以及使用文本编辑器 vim 和 emacs。

使用 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 中并排查看文件。


相关文章


有用资源