Diff

Diff

diff

В вычислительной технике diff — утилита сравнения файлов, выводящая разницу между двумя файлами. Эта программа выводит построчно изменения, сделанные в файле (для текстовых файлов). Современные реализации поддерживают также двоичные файлы. Вывод утилиты называется «diff», или, что более распространено, патч, так как он может быть применён с программой patch. Вывод похожих утилит сравнения файлов также часто называется «diff».

Содержание

История

Утилита diff была разработана в начале 1970-х годов для операционной системы Unix, которая была плодом работы AT&T Bell Labs, в Мюррей Хилл (Нью-Джерси). Финальная версия, распространяемая с 5ой версией Unix в 1974, была полностью написана Даглас МэкИлрой (англ.).

Алгоритм

Работа diff основана на нахождении наибольшей общей подпоследовательности (англ. longest common subsequence, проблема LCS). Например, у вас имеется две последовательности элементов:

       a b c d f g h j q z
       a b c d e f g i j k r x y z

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

       a b c d f g j z

После получения наибольшей общей последовательности остаётся только небольшой шаг до получения похожего на diff вывода:

       e   h i   k   q r x y 
       +   - +   +   - + + +

Использование

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

original:

This part of the
document has stayed the
same from version to
version.  It shouldn't
be shown if it doesn't
change.  Otherwise, that
would not be helping to
compress the size of the
changes.
This paragraph contains
text that is outdated.
It will be deleted in the
near future.
It is important to spell
check this dokument. On
the other hand, a
misspelled word isn't
the end of the world.
Nothing in the rest of
this paragraph needs to
be changed. Things can
be added after it.

new:

This is an important
notice! It should
therefore be located at
the beginning of this
document!
This part of the
document has stayed the
same from version to
version.  It shouldn't
be shown if it doesn't
change.  Otherwise, that
would not be helping to
compress anything.
It is important to spell
check this document. On
the other hand, a
misspelled word isn't
the end of the world.
Nothing in the rest of
this paragraph needs to
be changed. Things can
be added after it.
This paragraph contains
important new additions
to this document.

Команда diff original new производит следующий нормальный дифф-вывод:

0a1,6
> This is an important
> notice! It should
> therefore be located at
> the beginning of this
> document!
>
8,14c14
< compress the size of the
< changes.
<
< This paragraph contains
< text that is outdated.
< It will be deleted in the
< near future.
---
> compress anything.
17c17
< check this dokument. On
---
> check this document. On
24a25,28
>
> This paragraph contains
> important new additions
> to this document.

В этом традиционном формате вывода a означает добавлено (от англ. add), d — удалено, с — изменено. Перед буквами a, d или c стоят номера строк исходного файла, после них — номера строк конечного файла. Каждая строка, которая была добавлена, удалена или изменена, предваряется угловыми скобками.

По умолчанию, общие для исходного и конечного файлов номера строк не указываются. Строки, которые перемещены, показываются как добавленные на своём новом месте и удалённые из своего прошлого расположения.[1]

Варианты

Большинство реализаций diff остаются внешне неизменными с 1975 года. Модификации включают в себя улучшения основного алгоритма, добавление новых ключей команды, новые форматы вывода. Базовый алгоритм изложен в книгах An O(ND) Difference Algorithm and its Variations Юджина В. Майерса, [2] и в A File Comparison Program Вебба Миллера и Майерса. [3] Алгоритм был независимо открыт и описан в Algorithms for Approximate String Matching Е. Укконеном [4] Первые версии программы diff были разработаны для сравнения строк текстовых файлов, использующий символ новой строки как разделитель строк. В 1980-х, поддержка двоичных файлов привела к изменениям в схеме работы и реализации программы.

Контекстный формат

В BSD версии 2.8 (выпущенной в июле 1981 года) появился контекстный формат (-c).

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

Вывод команды diff -c original new:

*** /path/to/original ''timestamp''
--- /path/to/new      ''timestamp''
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
+
  This part of the
  document has stayed the
  same from version to
***************
*** 5,20 ****
  be shown if it doesn't
  change.  Otherwise, that
  would not be helping to
! compress the size of the
! changes.
!
! This paragraph contains
! text that is outdated.
! It will be deleted in the
! near future.
 
  It is important to spell
! check this dokument. On
  the other hand, a
  misspelled word isn't
  the end of the world.
--- 11,20 ----
  be shown if it doesn't
  change.  Otherwise, that
  would not be helping to
! compress anything.
 
  It is important to spell
! check this document. On
  the other hand, a
  misspelled word isn't
  the end of the world.
***************
*** 22,24 ****
--- 22,28 ----
  this paragraph needs to
  be changed. Things can
  be added after it.
+
+ This paragraph contains
+ important new additions
+ to this document.

Унифицированный формат

Другие форматы

См. также

Примечания

  1. Comparing and Merging Files with GNU Diff and Patch. — 1997. — ISBN ISBN 0-9541617-5-0
  2. E. Myers (1986). «An O(ND) Difference Algorithm and Its Variations». Algorithmica 1 (2): 251–266.
  3. Webb Miller and Eugene W. Myers (1985). «A File Comparison Program». Software — Practice and Experience 15 (11): 1025–1040.
  4. E. Ukkonen (1985). «Algorithms for Approximate String Matching». Information and Control 64: 100–118.

Ссылки



Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Полезное


Смотреть что такое "Diff" в других словарях:

  • diff — ist ein Unix Programm, das die Unterschiede zwischen zwei Textdateien zeilen bzw. abschnittweise einander gegenüberstellt. Inhaltsverzeichnis 1 Grundlagen 2 Programmfunktion 2.1 Aufruf 2.2 A …   Deutsch Wikipedia

  • Diff — ist ein Unix Programm, das synoptisch die Unterschiede zwischen zwei Textdateien zeilen bzw. abschnittweise einander gegenüberstellt. Inhaltsverzeichnis 1 Grundlagen 2 Programmfunktion 2.1 Aufruf 2.2 Ausgabe 3 Gesch …   Deutsch Wikipedia

  • Diff — Saltar a navegación, búsqueda En informática, diff es una utilidad para la comparación de archivos que genera las diferencias entre dos archivos o los cambios realizados en un archivo determinado comparándolo con una versión anterior del mismo… …   Wikipedia Español

  • diff — est une commande Unix qui permet de comparer deux fichiers et d en afficher les différences. La première version de diff a été livrée avec la 5e édition d Unix en 1974, elle avait été écrite par Douglas McIlroy. L article de recherche a été… …   Wikipédia en Français

  • Diff — est une commande Unix qui permet de comparer deux fichiers et d en afficher les différences. La première version de diff a été livrée avec la 5e édition d Unix en 1974, elle avait été écrite par Douglas McIlroy. L article de recherche a été… …   Wikipédia en Français

  • diff — or dif [dif] n. [Slang] short for DIFFERENCE [what s the diff?] * * * diff (dĭf) n. Informal Difference: “[His] flaw... starts with a fleshy calculation, an instinct to blunt disagreeme …   Universalium

  • DIFF — may refer to: diff, a file comparison utility Dominican International Film Festival Dubai International Film Festival This disambiguation page lists articles associated with the same title. If an …   Wikipedia

  • diff — or dif [dif] n. [Slang] short for DIFFERENCE [what s the diff?] …   English World dictionary

  • Diff — In computing, diff is a file comparison utility that outputs the differences between two files, or the changes made to a current file by comparing it to a former version of the same file. Diff displays the changes made per line for text files.… …   Wikipedia

  • diff — This article is about the file comparison utility. For other uses, see DIFF (disambiguation). Diffs redirects here. For the American punk rock group, see The Diffs. In computing, diff is a file comparison utility that outputs the differences… …   Wikipedia


Поделиться ссылкой на выделенное

Прямая ссылка:
Нажмите правой клавишей мыши и выберите «Копировать ссылку»