linux shell 查找文件差异并进行修补

本文介绍如何利用diff命令查看两个文件的差异,并通过patch命令将这些差异应用于另一个文件,实现文件内容的更新。具体展示了如何生成一体化的diff输出以便于阅读,并通过实例说明了diff和patch的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例:
[root@localhost test]# cat A.txt 
1
2
5
[root@localhost test]# cat B.txt 
1
3
6

[root@localhost test]# diff A.txt B.txt -u
--- A.txt       2012-05-19 11:09:01.000000000 +0800
+++ B.txt       2012-05-19 11:09:25.000000000 +0800
@@ -1,3 +1,3 @@
 1
-2
-5
+3
+6
其中加上-u是生成一体化输出,这样易读性更好,更易于看出两个文件之间的差异。
在一体化的diff中,以+起始的行表示是新加入的行,-起始的行表示被删除的行。
将一体化的修补文件,重定向到一个新文件,得到修补文件:
[root@localhost test]# diff A.txt B.txt -u > version.patch
将修补谁的用于A.txt,会将A.txt修改为B.txt:
[root@localhost test]# patch -p1 A.txt < version.patch 
missing header for unified diff at line 3 of patch
patching file A.txt
[root@localhost test]# cat A.txt 
1
3
6
同样,将修被文件用于B.txt,会将B.txt修改为A.txt:
[root@localhost test]# patch -p1 B.txt < version.patch 
missing header for unified diff at line 3 of patch
patching file B.txt
Reversed (or previously applied) patch detected!  Assume -R? [n] y
[root@localhost test]# cat B.txt
1
2
5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值