一、diff 命令简介
diff 命令是一个用于比较两个文件并输出它们之间差异的工具。它是文件比较的基本工具,广泛用于源代码管理、脚本编写和日常的文件维护工作中。
二、diff 命令参数
diff [选项] 文件1 文件2
选项:
-
-b 或--ignore-space-change:忽略空白区的差异。 -
-B 或--ignore-blank-lines:忽略空白行的差异。 -
-i 或--ignore-case:忽略大小写的差异。 -
-w 或--ignore-all-space:忽略所有空白字符的差异。 -
-r 或--recursive:递归比较目录中的文件。 -
-q 或--brief:仅报告文件是否不同,不显示详细差异。 -
-y 或--side-by-side:并排显示文件的差异。 -
-c:以上下文格式显示差异。 -
-u 或--unified:以统一格式显示差异,通常用于补丁文件。
输出含义:
-
a:添加 -
c:更改 -
d:删除 -
<:左边文件 -
>:右边文件 -
---:第一个文件名 -
+++:第二个文件名 -
n,m:从第 n 行到第 m 行
diff 命令的输出可以用来生成补丁(patch),然后使用 patch 命令将这些差异应用到文件上。
三、diff 命令示例
下面我将提供两个简单的文本文件 file1.txt 和 file2.txt 的内容,并展示使用 diff 命令比较这两个文件时的输出。
假设 file1.txt 的内容如下:
Hello World
Linux is great
This is a test file
而 file2.txt 的内容如下(在 file1.txt 的基础上修改第 2,3 行):
Hello World
Linux is fantastic
This is a test document
1 比较两个文件
命令
diff file1.txt file2.txt
输出
2,3c2,3
< Linux is great
< This is a test file
---
> Linux is fantastic
> This is a test document
2 忽略空白字符差异
命令
diff -w file1.txt file2.txt
3 并排显示差异
命令
diff -y file1.txt file2.txt
输出
Hello World Hello World
Linux is great | Linux is fantastic
This is a test file | This is a test document
4 以统一格式显示差异
命令
diff -u file1.txt file2.txt
输出
--- file1.txt 2024-09-14 13:48:02.119907008 +0000
+++ file2.txt 2024-09-14 13:48:17.331776326 +0000
@@ -1,3 +1,3 @@
Hello World
-Linux is great
-This is a test file
+Linux is fantastic
+This is a test document
5 递归比较两个目录
diff -r dir1 dir2
在使用 diff 命令的时候,像 zsh 这样给予颜色提示的 shell 更加友好
注意事项
-
diff命令在比较大型文件或目录时可能会产生大量输出,建议结合使用选项来过滤结果。 - 对于大型文件或目录的比较,考虑使用其他工具或方法来提高效率。



![[Visual Stuidio 2022使用技巧]2.配置及常用快捷键](https://i-blog.csdnimg.cn/direct/b77d60230ede4861aab11df33af268df.png)






![[XILINX] 正点原子ZYNQ7015开发板!ZYNQ 7000系列、双核ARM、PCIe2.0、SFPX2,性能强悍,资料丰富!](https://i-blog.csdnimg.cn/direct/28c8e7d2ff3543038baa153a62eb90fa.jpeg#pic_center)








