Linux show files diff

Сравнение файлов в 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. В выводе утилиты кроме, непосредственно, отображения изменений, выводит строку в которой указывается в какой строчке и что было сделано. Для этого используются такие символы:

  • a — добавлена;
  • d — удалена;
  • c — изменена.

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

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

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

diff file1 file2

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

diff -i file1 file2

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

diff -y file1 file2

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

diff -u file1 file2

Чтобы обработать несколько файлов в папке удобно использовать опцию -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 или даже сравнить каталоги. Кроме того, есть поддержка слияния и ручного выравнивания.

Читайте также:  Как найти пароль от вай фая принтера hp

5. TkDiff

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

Выводы

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

Источник

diff command in Linux with examples

diff stands for difference. This command is used to display the differences in the files by comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one file have is to be changed to make the two files identical.

The important thing to remember is that diff uses certain special symbols and instructions that are required to make two files identical. It tells you the instructions on how to change the first file to make it match the second file.

Special symbols are:

Syntax :

Lets say we have two files with names a.txt and b.txt containing 5 Indian states.

Now, applying diff command without any option we get the following output:

Let’s take a look at what this output means. The first line of the diff output will contain:

  • Line numbers corresponding to the first file,
  • A special symbol and
  • Line numbers corresponding to the second file.

Like in our case, 0a1 which means after lines 0(at the very beginning of file) you have to add Tamil Nadu to match the second file line number 1. It then tells us what those lines are in each file preceded by the symbol:

  • Lines preceded by a are lines from the second file.
  • Next line contains 2,3c3 which means from line 2 to line 3 in the first file needs to be changed to match line number 3 in the second file. It then tells us those lines with the above symbols.
  • The three dashes (“—“) merely separate the lines of file 1 and file 2.

As a summary to make both the files identical, first add Tamil Nadu in the first file at very beginning to match line 1 of second file after that change line 2 and 3 of first file i.e. Uttar Pradesh and Kolkata with line 3 of second file i.e. Andhra Pradesh. After that change line 5 of first file i.e. Jammu and Kashmir with line 5 of second file i.e. Uttar Pradesh.

Now let’s see what it looks like when diff tells us that we need to delete a line.

Here above output 3d2 means delete line 3rd of first file i.e. Telangana so that both the files sync up at line 2.

Options

Linux system offers two different ways to view the diff command output i.e. context mode and unified mode.

1. -c (context) : To view differences in context mode, use the -c option. Lets try to understand this with example, we have two files file1.txt and file2.txt:

The first file is indicated by ***, and the second file is indicated by .
The line with *************** is just a separator.

The first two lines of this output show us information about file 1 and file 2. It lists the file name, modification date, and modification time of each of our files, one per line.
The next line has three asterisks *** followed by a line range from the first file (in our case lines 1 through 4, separated by a comma). Then four asterisks ****. After that it shows the contents of the first file with the following indicators:

(i) If the line needs to be unchanged, it is prefixed by two spaces.
(ii) If the line needs to be changed, it is prefixed by an symbol and a space. The symbol means are as follows:

(a) + : It indicates a line in the second file that needs to be added to the first file to make them identical.
(b) – : It indicates a line in the first file that needs to be deleted to make them identical.
Like in our case, it is needed to delete mv and comm from first file and add diff and comm to the first file to make both of them identical.

Читайте также:  Картридж 20sl 1 микрон

After that there are three dashes followed by a line range from the second file (in our case lines 1 through 4, separated by a comma). Then four dashes —-. Then it shows the contents of the second file.

2. -u (unified) : To view differences in unified mode, use the -u option. It is similar to context mode but it doesn’t display any redundant information or it shows the information in concise form.

The first file is indicated by , and the second file is indicated by +++.
The first two lines of this output show us information about file 1 and file 2. It lists the file name, modification date, and modification time of each of our files, one per line.
After that the next line has two at sign @ followed by a line range from the first file (in our case lines 1 through 4, separated by a comma) prefixed by and then space and then again followed by a line range from the second file prefixed by + and at the end two at sign @. Followed by the file content in output tells us which line remain unchanged and which lines needs to added or deleted(indicated by symbols) in the file 1 to make it identical to file 2.

3. -i : By default this command is case sensitive. To make this command case in-sensitive use -i option with diff.

4. –version : This option is used to display the version of diff which is currently running on your system.

Источник

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

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.

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.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector