Predictive Hacks

How to Compare and Update files in Unix with diff and patch commands

Let’s say that we want to compare two files in Unix. The first.R and the final.R which are the:

first.R

my_models<-list()
 
for (s in unique(iris$Species)) {
    tmp<-iris[iris$Species==s,]
    my_models[[s]]<-lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width, data=tmp)
}

my_models

final.R

# create an empty list
# to store the models
my_models<-list()
 
for (s in unique(iris$Species)) {
    tmp<-iris[iris$Species==s,]
    my_models[[s]]<-lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width, data=tmp)
}
 
# get the 'setosa' model
my_models[['setosa']]

Compare the files using the diff command

In Unix, we can run the diff command as follows:

$ diff -u first.R final.R

And we get:

$ diff -u first.R final.R
--- first.R     2021-02-21 13:47:57.875639200 +0200
+++ final.R     2021-02-21 13:46:59.259101400 +0200
@@ -1,8 +1,11 @@
+# create an empty list
+# to store the models
 my_models<-list()

 for (s in unique(iris$Species)) {
     tmp<-iris[iris$Species==s,]
     my_models[[s]]<-lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width, data=tmp)
 }
-
-my_models
\ No newline at end of file
+
+# get the 'setosa' model
+my_models[['setosa']]
\ No newline at end of file

where the -- are referred to the first.R and the ++ to the final.R. So, it tells us which lines have been added and which lines have been removed.

Create a file of differences

You can create a patch file with the differences between the old and new file as follows:

$ diff -u first.R final.R > diff_file.patch

Update the file of differences with the patch command

If you have the difference file, like the diff_file.patch and your initial file like the first.R you can create the final.R as follows:

Let’s create a copy of the first.R

$ cp first.R first_mod.R

Now we can run the batch on the first_mod.R

$ patch first_mod.R < diff_file.patch

And the first_mod.R became identical to the final.R

You can confirm it by typing:

diff -u first_mod.R final.R

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s