Command to compare files in linux

How to Compare Two Files in Linux Terminal

The need for file comparison on a Linux operating system is often overlooked but has an important role to play especially for Linux system administrators. Being able to flexibly compare two files on a Linux terminal sheds some light on how unique or different a set of files are perceived to be.

[ You might also like: How to Join Two Text Files in Linux ]

For example, two files can exist with the same properties and size. Instead of making the assumption that they are identical, a Linux file comparison program will clear the air on such an issue. You could be surprised to find out that the differentiating factor of the two files is some wording or spacing that matches with one file and fails to do so with the other one.

Several terminal-based Linux programs can help us achieve the objective of this article but only a few stand out in terms of dynamic functionalities.

Creating Text Files in Linux

Let us create two sample files from the Linux terminal. Ensure that you are a sudoer user or have sudo privileges on the Linux operating system you are using.

We will populate this file with some random content.

1 2 3 4 5 6 7 8 9 10 one two three four five six seven eight nine ten This file contains some number sequences in numeric and textual form. Regards, LinuxShellTips Tutor

Let us create a second file.

We will populate this file with content slightly similar to file1.

11 2 13 4 15 6 7 8 19 10 one twice three four five six seven eight nine ten This file contains some number sequences in numeric form and some textual representation of the numbers. Regards, LinuxShellTips Tutor

Using diff to Compare Files in Linux

Since diff is a terminal-based program, using it outputs the targeted differences between two files. In other words, the diff output tells you the changes that can be implemented on file1 to make it a match or identical to file2.

Outputting the Differences between Two Files

Let us implement the first attempt into comparing these two files:

Compare Two Files in Linux

We can interpret this output in the following manner:

If you go back to the original file1 and file2 files we created earlier, you will note that the above diff command output is not displaying all the content from the two files. It has omitted all the similarities of the two files and only displayed their differences.

Читайте также:  Анимация в консоли линукс

Find Out Two Files are Identical Using Diff in Linux

Let us create a third file called file3.

We will populate this file with content similar to file1.

1 2 3 4 5 6 7 8 9 10 one two three four five six seven eight nine ten This file contains some number sequences in numeric and textual form. Regards, LinuxShellTips Tutor

A one-liner diff command output should be able to directly tell us if two files are identical.

Find Two Files are Identical Using Diff

The use of the extra -s command argument makes this output possible. However, implementing it with two unidentical files will still output their differences.

Find Differences Between Two Files

If you are looking for a one-liner output on two files you suspect to be different, consider the use of the diff command with the -q option.

$ diff -q file1 file2 Files file1 and file2 differ 

Diff Command Output Alternate View

If you need the output comparison of your two files to be side-by-side, consider implementing the diff command with the -y option.

Compare Two Files Side by Side

If you want the above command to suppress or ignore the similarities of the two files, include the —suppress-common-lines option.

$ diff -y --suppress-common-lines file1 file2

If you are dealing with two large files and want to limit the output to specific column numbers, you would implement the diff command in the following manner.

Compare Two Files by Column

The above command assumes the two files in comparison are somewhat large and exceed 50 columns in terms of text size. The diff output will be limited to 50 columns.

Источник

Linux diff – How to Compare Two Files and Apply Changes with the Patch Command

Zaira Hira

Zaira Hira

Linux diff – How to Compare Two Files and Apply Changes with the Patch Command

Imagine waking up one day to find out that your production systems are down because of a bug that has yet to be traced. One of your worst nightmares right?

And you also discover that you need to compare code from two versions and the pressure is building to restore the systems. Everyone is panicking and it’s totally legit!

Luckily, there is a Linux utility called diff that has got your back.

What is the diff command in Linux?

Comparing files and finding the differences between them is a widely used operation. This is specially useful when you have to compare complex code or configuration files.

Instead of comparing manually (which has a high chance of human error), Linux gives you a built in and powerful utility called diff . It also saves time.

To compliment diff commands, Linux also provides another command to apply changes from one file to another called patch . In this article, we’ll be looking into these interesting and versatile commands to see how to use them.

diff command syntax

The syntax for diff is shared below:

image-63

In the next example, there are two files that don’t have the same contents. In the output highlighted below, the diff command shows that lines 11 and 14 in showList_v2.js should change to match lines 11 and 13 in showList_v1.js.

image-64

The next way you can use diff is my favorite, as you can see differences side by side.

Читайте также:  Синхронизация google drive linux

Just use the -y flag like this:

image-50

The last example I am going to discuss is unified output. This output is often used as input to the patch command. We’ll see how the patch command works as well:

image-67

Below are some other useful flags you can use with diff .

  • -i to ignore case. diff is case sensitive by default.
  • -w to ignore whitespaces in a file. By default whitespaces are considered a difference.

patch Command Syntax

Changes happen all the time in your code, and it is unrealistic and time-consuming to share edited and fixed files for each change. Usually devs share fixes in the code with the team so they are applied instantly.

And using patches is the safest method to distribute improvements only.

Let’s see how patching works:

image-68

However, there is something wrong in the print function and we need a fixture for that. We send the file print_in_js.js to our colleague who fixes the code and sends it back.

First, our colleague is able to find a type in line #3. They correct the file.

Once file is corrected, and the code is functional, they create a patch.

image-69

Once we have the patch, we apply it as follows:

image-72

And yes – our code is fixed!

Wrapping Up

It is relatively simple and straightforward to create and apply patches using patch and diff .

A similar approach works when you’re using version control systems like Git or SVN. Learning the basics really helps you transition to and understand how version control works, which is an important aspect of software development.

Thanks for reading until the end. I would love to connect with you. You can find me here on twitter. Do share your thoughts.

Источник

Сравнение файлов в Linux

Иногда возникает необходимость сравнить несколько файлов между собой. Это может понадобиться при анализе разницы между несколькими версиями конфигурационного файла или просто для сравнения различных файлов. В Linux для этого есть несколько утилит, как для работы через терминал, так и в графическом интерфейсе.

В этой статье мы рассмотрим как выполняется сравнение файлов Linux. Разберем самые полезные способы, как для терминала, так и в графическом режиме. Сначала рассмотрим как выполнять сравнение файла linux с помощью утилиты diff.

Сравнение файлов diff

Утилита diff linux — это программа, которая работает в консольном режиме. Ее синтаксис очень прост. Вызовите утилиту, передайте нужные файлы, а также задайте опции, если это необходимо:

$ diff опции файл1 файл2

Можно передать больше двух файлов, если это нужно. Перед тем как перейти к примерам, давайте рассмотрим опции утилиты:

  • -q — выводить только отличия файлов;
  • -s — выводить только совпадающие части;
  • — выводить нужное количество строк после совпадений;
  • -u — выводить только нужное количество строк после отличий;
  • -y — выводить в две колонки;
  • -e — вывод в формате ed скрипта;
  • -n — вывод в формате RCS;
  • -a — сравнивать файлы как текстовые, даже если они не текстовые;
  • -t — заменить табуляции на пробелы в выводе;
  • -l — разделить на страницы и добавить поддержку листания;
  • -r — рекурсивное сравнение папок;
  • -i — игнорировать регистр;
  • -E — игнорировать изменения в табуляциях;
  • -Z — не учитывать пробелы в конце строки;
  • -b — не учитывать пробелы;
  • -B — не учитывать пустые строки.
Читайте также:  Linux with only terminal

Это были основные опции утилиты, теперь давайте рассмотрим как сравнить файлы Linux. В выводе утилиты кроме, непосредственно, отображения изменений, выводит строку в которой указывается в какой строчке и что было сделано. Для этого используются такие символы:

К тому же, линии, которые отличаются, будут обозначаться символом .

Вот содержимое наших тестовых файлов:

Теперь давайте выполним сравнение файлов diff:

В результате мы получим строчку: 2,3c2,4. Она означает, что строки 2 и 3 были изменены. Вы можете использовать опции для игнорирования регистра:

Можно сделать вывод в две колонки:

А с помощью опции -u вы можете создать патч, который потом может быть наложен на такой же файл другим пользователем:

Чтобы обработать несколько файлов в папке удобно использовать опцию -r:

Для удобства, вы можете перенаправить вывод утилиты сразу в файл:

diff -u file1 file2 > file.patch

Как видите, все очень просто. Но не очень удобно. Более приятно использовать графические инструменты.

Сравнение файлов Linux с помощью GUI

Существует несколько отличных инструментов для сравнения файлов в linux в графическом интерфейсе. Вы без труда разберетесь как их использовать. Давайте рассмотрим несколько из них:

1. Kompare

Kompare — это графическая утилита для работы с diff, которая позволяет находить отличия в файлах, а также объединять их. Написана на Qt и рассчитана в первую очередь на KDE. Кроме сравнения файлов утилита поддерживает сравнение каталогов и позволяет создавать и применять патчи к файлам.

2. Meld

Это легкий инструмент для сравнения и объединения файлов. Он позволяет сравнивать файлы, каталоги, а также выполнять функции системы контроля версий. Программа создана для разработчиков и позволяет сравнивать до трёх файлов. Можно сравнивать каталоги и автоматически объединять сравниваемые файлы. Кроме того поддерживаются такие системы контроля версий, как Git.

3. Diffuse

Diffuse — еще один популярный и достаточно простой инструмент для сравнения и слияния файлов. Он написан на Python 2. Поэтому в современных версиях Ubuntu программу будет сложно установить. Поддерживается две основные возможности — сравнение файлов и управление версиями. Вы можете редактировать файлы прямо во время просмотра.

4. KDiff3

KDiff3 — еще один отличный, свободный инструмент для сравнения файлов в окружении рабочего стола KDE. Он входит в набор программ KDevelop и работает на всех платформах, включая Windows и MacOS. Можно выполнить сравнение до трех файлов Linux или даже сравнить каталоги. Кроме того, есть поддержка слияния и ручного выравнивания.

5. TkDiff

Это очень простая утилита для сравнения файлов написанная на основе библиотеки tk. Она позволяет сравнивать только два файла, поддерживает поиск и редактирование сравниваемых файлов.

Выводы

В этой статье мы рассмотрели как выполняется сравнение файлов linux с помощью терминала, как создавать патчи, а также сделали небольшой обзор лучших графических утилит для сравнения файлов. А какие инструменты для сравнения используете вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector