Skip to main content

Command Palette

Search for a command to run...

Linux command: Diff/Patch

Published
2 min read

diff will calculate the difference of two files or folders and output with specific format. patch parse that specific format and apply difference to files or folders.

Example for Files

Here we prepare two files: file1.old.cpp and file1.new.cpp

// file1.old.cpp  
#include <iostream>

int main() {  
    return 0;  
}
// file1.new.cpp  
#include <iostream>

int main() {  
    std::cout << "hello world" << std::endl;  
    return 0;  
}

Then the command can be:

diff -Naur file1.old.cpp file1.new.cpp > patch.diff

The patch.diff will be:

--- file1.old.cpp    2021-11-03 14:32:34.000000000 +0800  
+++ file1.new.cpp    2021-11-03 14:33:00.000000000 +0800  
@@ -1,5 +1,6 @@  
 #include <iostream>

int main() {  
**+    std::cout << "hello world" << std::endl;  
**    return 0;  
 }  
\\ No newline at end of file

-Naur Parameters

  • N: Treat removed file as empty.
    This parameter allow patch command to remove or create files.
  • a: Allow calculating difference of binary file.
  • r: Recursively visit the folder tree.
  • u: Specific format output of difference.

-u: Specific format

Without this parameter, we’ll get the format below, and the patch command cannot parse it.

$ diff file1.old.cpp file1.new.cpp > patch.diff  
$ cat patch.diff  
3a4  
>     std::cout << "hello world" << std::endl;  
$ patch -p0 < patch.diff  
patch: **** Only garbage was found in the patch input.

Example for Folder

old  
├── main.cpp (file1.old.cpp)  
└── legacy  
      └── 1.txt
new  
└── main.cpp (file1.new.cpp)

This example has a absent file: old/legacy/1.txt and diff treat new/legacy/1.txt as an empty file with timestamp = unix time 0.

diff -Naur old/legacy/1.txt new/legacy/1.txt  
--- old/legacy/1.txt    2021-11-03 14:47:46.000000000 +0800  
+++ new/legacy/1.txt    **1970-01-01 08:00:00.000000000 +0800**  
@@ -1 +0,0 @@  
\-123  
\\ No newline at end of file  
diff -Naur old/main.cpp new/main.cpp  
--- old/main.cpp    2021-11-08 11:55:32.000000000 +0800  
+++ new/main.cpp    2021-11-08 11:55:35.000000000 +0800  
@@ -1,5 +1,6 @@  
 #include <iostream>

int main() {  
+    std::cout << "hello world" << std::endl;  
    return 0;  
 }  
\\ No newline at end of file

Patch

Patch old version to new version:

diff -Naur file1.old.cpp file1.new.cpp > patch.diff  
patch -p0 < patch.diff

“Patch” new version to old version:

patch -p0 < patch.diff -R

Reference

More from this blog

簡介 C++ 的 Type Erase (用多型和模板做 Duck Type)

起點 讓我們先從 template 出發:foo 需要一個 callback function。 template<typename Func> void foo(Func callback) { // ... callback(); } 但是這會讓編譯錯誤訊息有點模糊:假如 callback 並不是一個可以呼叫的函數指標,或者並不是一個 callable object ,那編譯器會說錯出在第四行。但是我們都希望,編譯器在呼叫函數時就幫我們指出:這不是 foo 想要的 call...

May 14, 20243 min read

帕秋莉的魔法筆記

45 posts

後端工程師。

不定時張貼一些寫扣時的筆記。

Linux command: Diff/Patch