Linux文件比对diff

Linux Diff 命令

diff [OPTION]... FILES

[OPTION]表示多个命令行选项,FILES 通常是2个文件名

Diff 用法

以下为2个我们想要比对的文件

file1:

test
test2
test3

file2:

test
test23
test3

比对这2个文件:

diff file1 file2

以上命令输出:

2c2
< test2
---
> test23

首先要记住的是,输出表示将file1(通常是原始文件)转换为file2(新文件或更改的文件)所需的更改。输出通常由以数字(或范围)开头,后跟字母(a,d或c)和另一个数字(或范围)的行组成。例如2c2(来自上面的输出)。

第一个数字代表从file1(原始文件)开始的行(或行的范围),而最后一个数字代表从file2(新文件)开始的行(或行的范围)。至于中间的字母,a表示添加,d表示删除,c表示更改。

因此,2c2表示原始文件中的第二行已更改,需要用新文件中的第二行替换才能使文件相同。如果您手动比较两个文件(文件1和文件2),那么您会发现情况确实如此。

至于上述示例中2c2后面的三行,以’<’开头的那一行是file1的第二行,而以’>’开头的那一行是文件2中的那一行。它们之间的三个连字符(—)仅用于分隔目的。

以下是另一个例子

file1

Hi all,
This is a diff command tutorial
from HowtoForge.
Hope you'll benefit from it.
Thanks.

file2

Hi all,
Welcome to HowtoForge.
In this tutorial, we'll discuss the diff tool.
Hope you'll find it beneficial.
Thanks.

比较命令

diff file1 file2

输出:

2,4c2,4
< This is a diff command tutorial
< from HowtoForge.
< Hope you'll benefit from it.
---
> Welcome to HowtoForge.
> In this tutorial, we'll discuss the diff tool.
> Hope you'll find it beneficial.

输出意味着原始文件(file1)中的行号2到4已更改

接下来,文件1的内容不变,改变文件2的内容如下

Welcome to HowtoForge.
In this tutorial, we'll discuss the diff tool.
Hope you'll find it beneficial.
Thanks.

Hi all,
This is a diff command tutorial
from HowtoForge.
Hope you'll benefit from it.
Thanks.

当执行比较命令的时候,输出如下

0a1,5
> Welcome to HowtoForge.
> In this tutorial, we'll discuss the diff tool.
> Hope you'll find it beneficial.
> Thanks.
>

因此,您可以看到该工具立即识别出file2中的第二段是file1包含的内容。因此,输出显示file2的第1至5行应附加在file1的开头,以使两个文件相同。

如果删除文件2的最后一行(“Thanks.”),将输出

0a1,5
> Welcome to HowtoForge.
> In this tutorial, we'll discuss the diff tool.
> Hope you'll find it beneficial.
> Thanks.
>
5d9
< Thanks.

您可以看到输出现在还包含5d9,这意味着应该删除file1中的第5行,以便使两个文件从第9行开始同步。当然,这是首先在0a1,5更改之后。

踏浪 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!