Linux diff命令示例
时间:2020-02-23 14:39:30 来源:igfitidea点击:
Linux diff命令逐行分析文件,并输出两个文件之间所做更改的列表。
diff命令是差异的缩写,从本质上讲,它给出了两个文件之间的差异。
与cmp
(compare)和comm
命令不同,diff突出显示需要更改以匹配其他文件的特定行。
Linux管理员不能忘记的一件事是,diff使用符号和说明来使其更加有效。
特定符号指示命令以特定方式更改文件以匹配第二种。
diff命令输出中的特殊符号:
- a:添加
- c:变更
- d:删除
Linux diff命令语法
diff [options] File1 File2
让我们看一下diff命令示例用法。
情况1:变更
假设我们有两个文件:x.txt和y.txt
x.txt包含以下内容。
California Miami Ohio Kansas Texas
y.txt包含以下内容。
California Nevada Georgia Kansas Texas
现在,使用diff命令在两个文件之间进行比较,如图所示。
$diff x.txt y.txt
让我们更详细地检查输出。
'2,3c2,3'行意味着第一个文件的第2行和第3行需要更改,以匹配第二个文本文件的第2行和第3行。
diff命令输出符号说明
让我们简要看看输出中遇到的各种符号。
- 小于符号表示从第一行开始的行
- 大于符号表示从第二行开始的行
a - Denotes that text was added to the file c - Denotes that changes were made in the file d - Indicates that the line was expunged or deleted
让我们来看另一个例子。
情况2:添加
我们有两个文本文件:
文件1.txt具有以下内容。
Linux is a great operating system It's free and opensource It's light and stable I would highly recommend it
file2.txt具有以下内容。
Linux is a great operating system It's free and opensource It's light and stable Oh ! It can be installed on almost any PC hardware I would highly recommend it
使用diff命令比较两个文件。
$diff file1.txt file2.txt
从上面的输出中," 3a4"表示第一个文件的第3行之后,需要添加另一行以匹配第二个文件的第4行。
情况3:删除
考虑如下两个文件。
具有以下内容的file3.txt。
Apples Oranges Mangoes Peaches Bananas Grapes
而file4.txt具有以下内容。
Apples Oranges Mangoes Bananas Grapes
同样,使用diff命令比较两个文件。
$diff file3.txt file4.txt
这里的输出4d3表示从第一个文件中删除第4行,以与第2行的第二个文件同步。