Linux terminal compare files

Сравнение файлов в Linux (команда diff)

Для сравнения двух или нескольких файлов в Linux есть команда diff . Она может сравнивать как отдельные файлы, так и каталоги. Рассмотрим синтаксис, опции команды diff и несколько примеров использования.

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

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

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

Опции команды diff

Рассмотрим основные опции команды diff. Я рассмотрю только те опции, которые сам использую наиболее часто.

-E игнорировать изменения, связанные с добавлением символа табуляции в тексте.
-b игнорировать изменения, связанные с добавлением пробелов.
-w игнорировать изменения, связанные с добавлением пробелов и табуляции.
-B игнорировать новые пустые строки.
-p (или —show-c-function) показать название функции языка C, в которой найдены изменения.
-y (или —side-by-side) отобразить результаты в две колонки.
-r просматривать каталоги рекурсивно.
-X FILE исключить из поиска файлы, имена которых совпадают с шаблонами в файле FILE.
-d (или —minimal) попытаться найти как можно меньше изменений (то есть исключить ложные срабатывания).

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

Сравнение двух текстовых файлов

Для простого сравнения двух текстовых файлов с именами myfile1 и myfile2 выполним в терминале команду:

Вывод команды diff удобно перенаправить в файл с расширением diff . Большинство текстовых редакторов в Linux, например Gedit, распознают этот файл и подсвечивают его синтаксис. Чтобы направить результат сравнения в файл changes.diff нужно использовать символ перенаправления потока (>):

Сравнение директорий, содержащих текстовые файлы

Рассмотрим пример сравнения двух директорий ( mydir1 и mydir2 ), которые содержат текстовые файлы. Основное отличие здесь от примера выше состоит в том, что мы добавим опцию -r , означающую рекурсивный обход файлов в директориях.

Теперь предположим, что в директориях, в которых мы сравниваем файлы, находится много «мусора», который мы не должны сравнивать. Создадим файл excludeFiles и запишем в него шаблоны и названия файлов, которые мы не должны сравнивать. Например, содержимое excludeFiles может иметь вид:

Теперь укажем команде diff, чтобы она использовала наш файл excludeFiles при сравнении каталогов:

Таким образом, мы сравниваем файлы, имена которых не попадают под шаблоны в файле excludeFiles , например, vasya.exe или ChangeLog12 .

Добавим еще несколько опций, которые описаны выше, чтобы улучшить результат сравнения:

Мы сравниваем файлы в директориях mydir1 и mydir2 , игнорируя изменения, связанные с добавлением пустых строк, пробелов, табуляции, а также используем шаблоны имен файлов в excludeFiles , чтобы исключить из сравнения ненужные файлы.

Заключение

Дополнительную информацию по использованию команды diff в вашей системе Linux вы можете получить, выполнив команду:

Также существуют программы, которые позволяют сравнивать файлы, используя графический интерфейс. Например, программа Meld, которая в наглядном виде показывает где и что изменилось в файлах.

Источник

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.

Читайте также:  Ожидание перезагрузки windows 10

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

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
Читайте также:  Дистрибутив windows 10 mobile

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.

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 Compare Two Text Files Using Linux

Test and see if your files have updated or changed

What To Know

  • To compare, run: diff file1 file2
  • Show how they’re different with: diff -q file1 file2
  • Show how they’re the same with: diff -s file1 file2

This article explains how to use Linux to compare two files and output the differences between the files to the screen or a file. You won’t install special software to compare files using Linux, but you need to know how to open a terminal window.

Create the Files to Compare

If you want to follow along with this guide, create two text files that contain similar but different text.

Create the First File

Create a file called file1 and then enter the following text:

To create this file, follow these instructions:

Open the file by typing the following command:

The quickest way to open a terminal window in Linux is to press the CTRL+ALT+T keys at the same time.

Type the text into the nano editor.

Press CTRL+O to save the file.

Press CTRL+X to exit the file.

Create the Second File

Next, create another file called file2 and enter the following text:

To create this file, follow these instructions:

Open the file by typing the following command:

Type the text into the nano editor.

Читайте также:  Случаи при установке windows

Press CTRL+O to save the file.

Press CTRL+X to exit the file.

How to Compare Two Files Using Linux

The command used in Linux to show the differences between two files is called the diff command.

The simplest form of the diff command is as follows:

If the files are the same, no output displays when using this command. However, as there are differences, the output is similar to the following:

Initially, the output seems confusing, but once you understand the terminology, it is fairly logical.

The differences between the two files are as follows:

  • The second file only has three lines. The first file has four.
  • The second file says 1 green bottle on the third line. The first file says one green bottle.
  • The second file says there’d instead of there would on the final line.

The output from the diff command shows that between lines two and four of the first file and lines two and three of the second file, there are differences.

It then lists the lines from two to four from the first file, followed by the two different lines in the second file.

How to Only Show If the Files Are Different

If you only want to know if the files are different and you aren’t interested in which lines are different, run the following command:

If the files are different, the following displays:

If the files are the same, nothing displays.

How to Show a Message If the Files Are the Same

When you run a command, you may want to know that it worked correctly. You want a message to display when you run the diff command whether the files are the same or different

To achieve this requirement using the diff command, use the following command:

If the files are the same, this message appears:

How to Produce the Differences Side by Side

If there are several differences, it can be confusing as to what the differences actually are between the two files. You can change the output of the diff command so that the results are shown side by side. To do this, run the following command:

The output for the file uses the | symbol to show a difference between the two lines, a to show a line that has been appended.

When you run the command using the demonstration files in this article, all the lines show as different except for the last line of file2, which is shown as deleted.

Restrict Column Width

When comparing two files side by side, it can be hard to read if the files have several columns of text. To restrict the number of columns, use the following command:

How to Ignore Case Differences When Comparing Files

If you want to compare two files, but you don’t care whether the case of the letters is the same between the two files, use the following command:

How to Ignore Trailing White Space at the End of a Line

If you notice many differences when comparing files and the differences are caused by white space at the end of the lines, prevent these from showing up as changes by running the following command:

How to Ignore All White Space Differences Between Two Files

If you are only interested in the text in a file and you don’t care whether there are more spaces in one than the other, use the following command:

How to Ignore Blank Lines When Comparing Two Files

If you don’t care that one file may have extra blank lines in it, compare the files using the following command:

Summary

You can find more information by reading the manual for the diff command.

The diff command can be used in its simplest form to show only the differences between two files. You can also use it to create a diff file as part of a patching strategy.

Another command you can use to compare files is the cmp command. This compares files byte by byte.

Источник

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