- Linux Shell Scripting Cookbook(Third Edition)
- Clif Flynt Sarath Lakshman Shantanu Tushar
- 278字
- 2021-07-09 19:46:35
How to do it...
The diff utility reports the differences between two files.
- To demonstrate diff behavior, create the following files:
File 1: version1.txt
this is the original text line2 line3 line4 happy hacking !
File 2: version2.txt
this is the original text line2 line4 happy hacking ! GNU is not UNIX
- Nonunified diff output (without the -u flag) is:
$ diff version1.txt version2.txt 3d2 <line3 6c5 > GNU is not UNIX
- The unified diff output is:
$ diff -u version1.txt version2.txt --- version1.txt 2010-06-27 10:26:54.384884455 +0530 +++ version2.txt 2010-06-27 10:27:28.782140889 +0530 @@ -1,5 +1,5 @@ this is the original text line2 -line3 line4 happy hacking ! - +GNU is not UNIX
The -u option produces a unified output. Unified diff output is more readable and is easier to interpret.
In unified diff, the lines starting with + are the added lines and the lines starting with - are the removed lines.
- A patch file can be generated by redirecting the diff output to a file:
$ diff -u version1.txt version2.txt > version.patch
The patch command can apply changes to either of the two files. When applied to version1.txt, we get the version2.txt file. When applied to version2.txt, we generate version1.txt.
- This command applies the patch:
$ patch -p1 version1.txt < version.patch patching file version1.txt
We now have version1.txt with the same contents as version2.txt.
- To revert the changes, use the following command:
$ patch -p1 version1.txt < version.patch patching file version1.txt Reversed (or previously applied) patch detected! Assume -R? [n] y #Changes are reverted.
As shown, patching an already patched file reverts the changes. To avoid prompting the user with y/n, we can use the -R option along with the patch command.