Shell – How to get character level difference using “diff” command in Linux using shell script

diff()shell-script

I have two SQL files, one is old.sql and the other one is new.sql.

Suppose old.sql contains a table with three fields, Emp_Id, Name and Address and data stored in old.sql as follows:

Insert into table1 values (101 ,"a", "xyz");
Insert into table1 values (102 ,"b", "pqr");

Then I have changed "a" address "xyz" to "xyz123" and saved that data in the new.sql file.
Now the new.sql file contains data as follows:

Insert into table1 values (101 ,"a", "xyz123");
Insert into table1 values (102 ,"b", "pqr");

When I use the diff command like this:

diff old.sql new.sql

it gives differences line-wise but I want only updated data, like xyz123.

Best Answer

You might find wdiff useful for this type of comparison; it's a front-end to diff which produces word-by-word comparisons. With your example it produces by default

Insert into table1 values (101 ,"a", [-"xyz");-] {+"xyz123");+}
Insert into table1 values (102 ,"b", "pqr");

It can use terminal features to make the output more legible on a terminal (wdiff -t). It also has a -3 option which limits output to changed words only:

======================================================================
 [-"xyz");-] {+"xyz123");+}
======================================================================

If you don't have wdiff already installed, you need to install it. Run sudo apt-get install wdiff or sudo dnf install wdiff or sudo yum install wdiff or the command that is appropriate to your operating system.

Related Question