What is diff in linux

9 Best File Comparison and Difference (Diff) Tools for Linux

While writing program files or normal text files, programmers and writers sometimes want to know the difference between two files or two versions of the same file. When you compare two computer files on Linux, the difference between their contents is called a diff. This description was born out of a reference to the output of diff, the well known Unix command-line file comparison utility.

9 Best Linux File Diff or Comparison Tools

There are several file comparison tools that you can use on Linux, and in this review, we shall look at some of the best terminal based and GUI diff tools you can take advantage of while writing code or other text files.

1. diff Command

I like to start with the original Unix command-line tool that shows you the difference between two computer files. Diff is simple and easy to use, it comes pre-installed on most Linux distributions. It compares files line by line and outputs the difference between them.

You can check out the manual entry for diff to easily use it.

Linux diff Command to Compare Files

There are some wrappers for the diff tool that enhance its functionality and these include:

colordiff Command

Colordiff is a Perl script that produces same output as diff, but with color and syntax highlighting. It has customizable color schemes.

You can install Colordiff on your Linux systems, using default package manager tools called yum, dnf or apt-get as shown.

You can check out the manual entry for Colordiff as shown.

Linux Colordiff Command – Color diff Output

wdiff Command

The wdiff utility is a front end to diff command used to compare files on a word by word basis. This program is very useful when comparing two texts for changed words and for which paragraphs have been refilled.

To install wdiff on your Linux systems, run:

Use wdiff manual for how to use it on Linux.

wdiff Compare Two Files in Linux

2. Vimdiff Command

Vimdiff works in an advanced manner in comparison to diff utility. It enables a user to edit up to four versions of a file while showing their differences. When you run it, Vimdiff opens two or three or four files using vim text editor.

Vimdiff Edit Multiple Files for Differences

Having looked the old school diff tools, lets quickly move to some GUI diff tools available on Linux.

3. Kompare

Kompare is a diff GUI wrapper that allows users to view differences between files and also merge them.

Some of its features include:

  1. Supports multiple diff formats
  2. Supports comparison of directories
  3. Supports reading diff files
  4. Customizable interface
  5. Creating and applying patches to source files

Kompare Tool – Compare Two Files in Linux

Читайте также:  Linux несколько версий python

4. DiffMerge

DiffMerge is a cross-platform GUI application for comparing and merging files. It has two functionality engines, the Diff engine which shows the difference between two files, which supports intra-line highlighting and editing and a Merge engine which outputs the changed lines between three files.

It has got the following features:

  1. Supports directory comparison
  2. File browser integration
  3. Highly configurable

DiffMerge – Compare Files in Linux

5. Meld – Diff Tool

Meld is a lightweight GUI diff and merge tool. It enables users to compare files, directories plus version controlled programs. Built specifically for developers, it comes with the following features:

  1. Two-way and three-way comparison of files and directories
  2. Update of file comparison as a users types more words
  3. Makes merges easier using auto-merge mode and actions on changed blocks
  4. Easy comparisons using visualizations
  5. Supports Git, Mercurial, Subversion, Bazaar plus many more

Meld – A Diff Tool to Compare File in Linux

6. Diffuse – GUI Diff Tool

Diffuse is another popular, free, small and simple GUI diff and merge tool that you can use on Linux. Written in Python, It offers two major functionalities, that is: file comparison and version control, allowing file editing, merging of files and also output the difference between files.

You can view a comparison summary, select lines of text in files using a mouse pointer, match lines in adjacent files and edit different file. Other features include:

  1. Syntax highlighting
  2. Keyboard shortcuts for easy navigation
  3. Supports unlimited undo
  4. Unicode support
  5. Supports Git, CVS, Darcs, Mercurial, RCS, Subversion, SVK and Monotone

DiffUse – A Tool to Compare Text Files in Linux

7. XXdiff – Diff and Merge Tool

XXdiff is a free, powerful file and directory comparator and merge tool that runs on Unix like operating systems such as Linux, Solaris, HP/UX, IRIX, DEC Tru64. One limitation of XXdiff is its lack of support for unicode files and inline editing of diff files.

It has the following list of features:

  1. Shallow and recursive comparison of two, three file or two directories
  2. Horizontal difference highlighting
  3. Interactive merging of files and saving of resulting output
  4. Supports merge reviews/policing
  5. Supports external diff tools such as GNU diff, SIG diff, Cleareddiff and many more
  6. Extensible using scripts
  7. Fully customizable using resource file plus many other minor features

xxdiff Tool

8. KDiff3 – – Diff and Merge Tool

KDiff3 is yet another cool, cross-platform diff and merge tool made from KDevelop. It works on all Unix-like platforms including Linux and Mac OS X, Windows.

It can compare or merge two to three files or directories and has the following notable features:

  1. Indicates differences line by line and character by character
  2. Supports auto-merge
  3. In-built editor to deal with merge-conflicts
  4. Supports Unicode, UTF-8 and many other codecs
  5. Allows printing of differences
  6. Windows explorer integration support
  7. Also supports auto-detection via byte-order-mark “BOM”
  8. Supports manual alignment of lines
  9. Intuitive GUI and many more

KDiff3 Tool for Linux

9. TkDiff

TkDiff is also a cross-platform, easy-to-use GUI wrapper for the Unix diff tool. It provides a side-by-side view of the differences between two input files. It can run on Linux, Windows and Mac OS X.

Additionally, it has some other exciting features including diff bookmarks, a graphical map of differences for easy and quick navigation plus many more.

Having read this review of some of the best file and directory comparator and merge tools, you probably want to try out some of them. These may not be the only diff tools available you can find on Linux, but they are known to offer some the best features, you may also want to let us know of any other diff tools out there that you have tested and think deserve to be mentioned among the best.

Читайте также:  Как установить запуск операционной системы windows

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to Find Difference Between Two Directories Using Diff and Meld Tools

In an earlier article, we reviewed 9 best file comparison and difference (Diff) tools for Linux and in this article, we will describe how to find the difference between two directories in Linux.

Normally, to compare two files in Linux, we use the diff – a simple and original Unix command-line tool that shows you the difference between two computer files; compares files line by line and it is easy to use, comes with pre-installed on most if not all Linux distributions.

The question is how do we get the difference between two directories in Linux? Here, we want to know what files/subdirectories are common in the two directories, those that are present in one directory but not in the other.

The conventional syntax for running diff is as follows:

By default, its output is ordered alphabetically by file/subdirectory name as shown in the screenshot below. In this command, the -q switch tells diff to report only when files differ.

Difference Between Two Directories

Again diff doesn’t go into the subdirectories, but we can use the -r switch to read the subdirectories as well like this.

Using Meld Visual Diff and Merge Tool

There is a cool graphical option called meld (a visual diff and merge tool for the GNOME Desktop) for those who enjoy using the mouse, you can install it as follows.

Once you have installed it, search for “meld” in the Ubuntu Dash or Linux Mint Menu, in Activities Overview in Fedora or CentOS desktop and launch it.

You will see the Meld interface below, where you can choose file or directory comparison as well as version control view. Click on directory comparison and move to the next interface.

Meld Comparison Tool

Select the directories you want to compare, note that you can add a third directory by checking the option “3-way Comparison”.

Select Comparison Directories

Once you selected the directories, click on “Compare”.

Listing Difference Between Directories

In this article, we described how to find the difference between two directories in Linux. If you know any other commandline or gui way don’t forget to share your thoughts to this article via the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Читайте также:  Crystal player для windows

Источник

Команда diff в Linux: сравниваем два файла

Представьте, что однажды утром вы просыпаетесь и обнаруживаете, чтоб ваши продакшен-системы «лежат» из-за бага, который только предстоит найти. Один из наихудших кошмаров, верно?

Также оказывается, что для восстановления системы вам нужно сравнить код в двух версиях. Давление растет, все вокруг паникуют (и это понятно).

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

Что из себя представляет команда diff в Linux?

Сравнение файлов и поиск различий между ними — широко распространенная операция. Она особенно полезна, когда нужно сравнить сложный код или конфигурационные файлы.

Сравнивать вручную долго и тяжело, к тому же велика вероятность ошибок. Поэтому Linux предоставляет вам мощную встроенную утилиту под названием diff. Ее применение позволяет сэкономить время и силы.

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

Синтаксис команды diff

Команда diff имеет следующий синтаксис:

Команда diff сравнивает два файла построчно. При этом первый из файлов она считает нуждающимся в редактировании и приведении к виду второго файла. Второй файл для diff — образец для сравнения.

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

Указания даются при помощи специальных символов:

  • c — CHANGE — изменение, которое нужно внести в указанной строке первого файла
  • d — DELETE — то, что нужно удалить в первом файле
  • a — ADD — то, что нужно добавить в первый файл

Символ в выводе diff указывает на первый файл, а > — на второй.

Давайте рассмотрим несколько примеров использования команды diff.

Примеры использования команды diff

Чтобы выяснить, являются ли файлы одинаковыми, команда diff дополняется флагом -s . В нашем примере содержимое файлов fileA и sameAsfileA совпадает.

А в следующем примере файлы имеют разный контент. Вывод команды diff говорит, что строки 11 и 14 в showList_v2.js нужно изменить, чтобы они совпадали со строками 11 и 13 в showList_v1.js.

Далее мы рассмотрим мой любимый способ использования команды diff — параллельный просмотр изменений. Для этого нужно применить флаг -y:

И последний пример — с объединенным выводом. Такой output часто используется как input для команды patch (ее мы тоже рассмотрим):

Вот еще несколько полезных флагов, которые можно применять с командой diff:

  • -i — для игнорирования регистра. По умолчанию команда diff учитывает регистр.
  • -w — для игнорирования пробелов в файле. По умолчанию пробелы тоже учитываются и могут считаться различием.

Синтаксис команды patch

Изменения в коде происходят постоянно. Расшаривать отредактированные файлы после внесения каждого изменения нереально. Обычно разработчики расшаривают сами изменения в коде.

Использование патчей («заплаток») — самый безопасный способ делиться только лишь изменениями.

Давайте посмотрим, как работают патчи:

Примеры использования команды patch

Предположим, у нас есть простой JavaScript-код в файле print_in_js.js, который выводит строку.

Но в функции вывода что-то сломалось, и нам нужно внести исправления. Мы отсылаем файл print_in_js.js коллеге, который может исправить код.

Наш коллега находит опечатку в строке № 3 и исправляет файл.

Когда файл исправлен и код работает корректно, наш коллега создает патч:

Давайте посмотрим содержимое патча:

Получив патч, мы применяем его:

И — вуаля! — наш код исправлен!

Итоги

Создавать и применять патчи при помощи команд patch и diff довольно просто.

Похожий подход применяется, когда вы пользуетесь системами контроля версий вроде Git или SVN. Знание основ (т. е. работы соответствующих команд Linux) поможет вам лучше понять работу систем контроля версий, а это важно для разработчиков.

Источник

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