日期:2014-05-16 浏览次数:20733 次
用了这么久linux,发现还有这么精妙的功能没有使用到,都不好意思跟人说我会linux了。
?
首先提供两个测试使用的简单文本文件
before.txt
This is a line to be deleted This is a line that will be changed This is a line that will be unchanged
?
?after.txt
This is a line that has been changed This is a line that will be unchanged This is a line that has been added
?
diff before.txt after.txt 1,2c1 < This is a line to be deleted < This is a line that will be changed --- > This is a line that has been changed 3a3 > This is a line that has been added
?
?说明:
1,2c1是指替换第1个文件的第1,2行到第2个文件的第2行,这里的1,2是指第1个文件的第1,2行,c是替换的意思,最后的1是第2个文件的第1行。
<号是指第1个文件更改或删除的行。
—号是分割两个文件。
>号是第2个文件中增加或删除的行。
3a3是指将第2个文件的第3行插入到第一个文件的第3行。也就是说第1个文件的:
< This is a line to be deleted < This is a line that will be changed
?
?被替换成第2个文件的:
> This is a line that has been changed
由于第1个文件的第3行和第2个文件的第2行一致,所以不做修改。
?
由于第2个文件的第3行是第1个文件所不具有的,所以在第1个文件的最后一行增加:
> This is a line that has been added
?
diff -u before.txt after.txt | tee mypatch.diff --- before.txt 2009-06-20 05:21:49.000000000 +0800 +++ after.txt 2009-06-20 04:03:16.000000000 +0800 @@ -1,3 +1,3 @@ -This is a line to be deleted -This is a line that will be changed +This is a line that has been changed This is a line that will be unchanged +This is a line that has been added
?
?说明:
diff -u选项是统一格式输出.
— before.txt 2009-06-20 05:21:49.000000000 +0800
— before.txt是指旧文件
+++ after.txt 2009-06-20 04:03:16.000000000 +0800
+++ after.txt是指新文件.
@@ -1,3 +1,3 @@
@@ -1,3是指第1个文件一共有3行,+1,3 @@是指第2个文件一共有3行.
-This is a line to be deleted -This is a line that will be changed
?
?是被删除的行
+This is a line that has been changed
?
?是增加的行
This is a line that will be unchanged
?
?没有-号和+号是指该行不变,因为after.txt和before.txt都有这行.
+This is a line that has been added
?是增加的行
?
diff的统一格式比较与输出是按顺序进行的。
?
diff before.txt after.txt > mypatch.txt
?
?用patch修补before.txt文件,使before.txt和after.txt一致.
cat mypatch.txt | patch before.txt patching file before.txt
?
?比较两个文件,现在是一致的了
cmp before.txt after.txt
?用patch命令恢复before.txt