Comparing files line by line can be done with a tool named diff. There are a lot of different options provided by diff. We will look at the most popular and useful features in this tutorial.
可以使用名为diff的工具逐行比较文件。 diff提供了许多不同的选项。 我们将在本教程中查看最受欢迎和最有用的功能。
句法 (Syntax)
diff
has simple syntax. There are options that we will look later and files to be compared.
diff
具有简单的语法。 有一些选项供我们稍后查看,并比较文件。
diff [OPTION] FILES
比较两个文件 (Compare Two Files)
In this example, we will compare two files line by line
在此示例中,我们将逐行比较两个文件
$ diff file1 file2
If there is no output after diff operation this means that there is no difference between files.
如果差异操作后没有输出,则表示文件之间没有差异。
In this output, we see that one line is different. > means the second file has one extra line
在此输出中,我们看到一行不同。 >表示第二个文件多了一行
3a4 means after line 3 line 4 is added
3a4表示在添加第3行,第4行之后
We change file and compare again with the same command
我们更改文件并再次使用同一命令进行比较
file1
文件1
This is line 1
We can resume
Extra file
Change the station
file2
文件2
This is line 1
We can resume
Change the station
Forth line
$ diff file1 file2
![Compare Two Files](https://i-blog.csdnimg.cn/blog_migrate/e6a49079721c6642f4b44ee2923fcaf4.png)
3d2 Lines 3 in the file1 need to be deleted in order to match line 2 in the file2
3d2文件1中的第3行需要删除,以便与文件2中的第2行匹配
4a4 From file2 delete line 4 to match first file line 4
4a4从file2删除第4行以匹配第一个文件第4行
查看详细差异(View Verbose Diff)
We can list all lines of two files with which lines will add or deleted both files to match each other.
我们可以列出两个文件的所有行,行将添加或删除这两个文件以使它们相互匹配。
$ diff -c file1 file2
![View Verbose Diff](https://i-blog.csdnimg.cn/blog_migrate/0e59cfb03e297310f1a507facb92a8cb.png)
统一模式(Unified Mode)
In a unified view, only one file is shown with related changes like delete or add. It is simpler than verbose mode to review.
在统一视图中,仅显示一个文件,其中包含相关的更改,例如删除或添加。 它比详细模式要简单得多。
$ diff -u file1 file2
![Unified Mode](https://i-blog.csdnimg.cn/blog_migrate/3498beaef178f4fbc9f1393b81787381.png)
翻译自: https://www.poftut.com/linux-diff-command-tutorial-with-examples-to-compare-two-text-file/