Saturday, January 18, 2014

using diff and patch commands in linux to get original/modified files

diff and patch tools are very useful while using version controlling applications.
Here I am going to explain a simple and powerful usage of patch command.

Lets say we have a file StringOne.java
Then we modified the file and committed the changes.
Lets assume that currently we have only two files:
1. diff file(between original and modified version)
2. file after modifications

Suppose after some days I want to view the original file before modifications. Since I do not have that, its not possible to view it directly as we didnt store it anywhere.
But with "patch" command, we can get it.

File Before modifications: PatchExample.java

package com.str1;

import java.io.*;

public class StringOne {
    static public void main(String[] args) {
        System.out.println("This is String one");
    }
}

File After modifications: PatchExample_p1.java

package com.str2;

public class StringOne {
    static public void main(String[] args) {
        System.out.println("This is String one");
        System.out.println("This is the extra line that got added...");
    }
}

diff file (original to modified): diff.patch
1,3c1
< package com.str1;
<
< import java.io.*;
---
> package com.str2;
7a6
>         System.out.println("This is the extra line that got added...");


Case 1: You have original file and diff file --> You want to get the modified file:

patch -i diff.patch -o PatchExample_p1.java PatchExample.java

This will produce a required new file named "PatchExample_p1.java".

Here:
    -i : input diff file name (diff.patch)
    -o : output file name to be generated (PatchExample_p1.java)
       : input file (PatchExample.java)

Case 2: You have modified file and diff file --> You want to get the original file:

patch -R -i diff.patch -o PatchExample.java PatchExample_p1.java

This will produce a required new file named "PatchExample.java".

Here:
    -R : does the reverse patching

No comments:

Post a Comment