FreeKB - View the differences between files using the DIFF command in Linux
View the differences between files using the DIFF command in Linux

Home > Search > Linux commands


The diff command can be used to determine if two different files or directories contain any differences.


Files

Let's say file1.txt contains FOO.

~]# cat file1.txt
FOO

 

And file2.txt contains BAR.

~]# cat file1.txt
BAR

 

The diff command will identify that the content of file1.txt and file2.txt are different.

~]# diff file1.txt file2.txt
< FOO
> BAR

 

  • Lines that begin with < exist in file1 but not in file2
  • Lines that begin with > exist in file2 but not in file1

 

By default, the diff command will compare lines in each file. For example, in line 1 in file 1 is not exactly the same as line 1 in file 2, then the diff command will spot these as different. Let's say file 1 contains "Hello World", and you want to determine if "Hello World" exists on any line in file 2. The -c option will accomplish this goal.

~]# diff -c file1 file2
! Lines that begin with ! exist in file1 but not in file2
  Lines that begin with a white space exist in file2 but not in file1

 


Directories

You can list all of the differences between files in two different directories.

~]# diff /path/to/directory1 /path/to/directory2

 

 


Recursive

The -r (recursive) option can be used to search for files that differ at and below a certain directory.

~]# diff -r /path/to/directory1 /path/to/directory2

 

 


Brief

Instead of listing all of the differences between files, you can instead just list the files that are in directory "a" but not in directory "b" and vice versa, and the files that are in both directories but have different content.

~]# diff --brief -r /path/to/directory1 /path/to/directory2

 


SSH / comparing files on different systems

Let's say you want to compare files on two different comptuers. If you are able to make an SSH connection from computer "a" to computer "b", you can use the following command to compare the differences.

ssh username@hostname "cat /path/to/file/on/remote/system" | diff - /path/to/file/on/local/system

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 2aaef in the box below so that we can be sure you are a human.




Comments