How to Compare Local and Remote Files in Linux
In this article, we will discuss how to compare or differentiate between local and remote files in Linux.
Programmers and writers often want to know the difference between two files or two copies of the same file when writing program files or regular text files. The discrepancy between the contents of two Linux machine files is referred to as a diff. A reference to the performance of diff, the well-known Unix command-line file comparison tool, inspired this definition.
diff (short for difference) is a simple and straightforward tool that compares two files line by line and shows the differences between them. It prints the lines that are different. Importantly, if you want the two files to be similar, diff also produces a collection of instructions for how to modify one file to make it identical to the other.
Let’s suppose you have two files :
file_local.txt
Hello World..!! Ubuntu CentOS Windows
Hello world..!! Kubuntu Ubuntu CentOS Windows
Run the following command to compare or identify the differences between two files on separate servers. Remember to change the user and remote host to your own values.
$ ssh user@remote_host “cat /home/root/remote_file” | diff – file_local
Output:
In Linux/Unix-like operating systems, the cat (short for “concatenate”) command is one of the most commonly used commands. We can use the cat command to build single or multiple files, display their contents, concatenate files, and redirect output to a terminal or files. You can also use the output redirection option to save the difference between the two files.
$ ssh user@remote_host “cat /home/root/remote_file” | diff – file_local > output_diff.txt
The contents of the diff output.txt file can then be viewed using the cat command.
$ cat output_diff.txt OR $ bcat output_diff.txt
Output:
You may also compare or notice the difference between two files on two different remote servers, as shown here:
$ diff <(ssh user@remote_host1 ‘cat /path/to/file_1’) <(ssh user@remote_host2 ‘cat /path/to/file_2’)
Consult the diff man page for more detail, as shown.
$ man diff
If you want to take a more visual approach to your terminal session, there exists a remote file system option and a visual file comparison option in the midnight commander for you. Many Linux systems do not have it installed by default, but it is available in most base repositories. Here are the steps to be taken:
- In the folder containing the file to be compared, run midnight commander (command: mc).
- Build an sftp connection to the other server in the same folder (sftp:/@/) on the other side (for example, the right menu).
- Select/highlight the files to be compared with the ins key. (The tab switches between the left and right panels.)
- Select Compare files from the Command menu.
In most terminal sessions, the midnight commander menu can be accessed by using the mouse. If that doesn’t work, F9 will take you to the menu.