- Linux Diff Command Tutorial with Examples To Compare Two Text File
- Syntax
- Compare Two Files
- View Verbose Diff
- Unified Mode
- Сравнение файлов в Linux (команда diff)
- Синтаксис команды diff
- Опции команды diff
- Примеры использования команды diff
- Сравнение двух текстовых файлов
- Сравнение директорий, содержащих текстовые файлы
- Заключение
- Best Diff Tools to Compare File Contents on Linux
- 1. Diff command
- 2. Wdiff
- 3. Vimdiff Command
- 4. Kompare
- 5. DiffMerge
- 6. Meld – Diff Tool
- 7. Diffuse – GUI Diff Tool
- 8. KDiff3 – – Diff and Merge Tool
- 9. TkDiff
- 10. Visual Studio code
- 11. Intellij Idea Community Edition
- 12. Beyond Compare
- 13. XXdiff – Diff and Merge Tool
- 14. Git Diff
- 15. P4Merge
- 16. Sublime Merge
- 17. DiffPlug
- 18. Code Compare
- 19. DiffPDF
- 20. Mergely
- Conclusion
Linux Diff Command Tutorial with Examples To Compare Two Text File
Comparing files line by line can be done with a tool named diff. There are a lot of different options provided by diff. We will look at the most popular and useful features in this tutorial.
Syntax
diff has simple syntax. There are options that we will look later and files to be compared.
Compare Two Files
In this example, we will compare two files line by line
If there is no output after diff operation this means that there is no difference between files.
In this output, we see that one line is different. > means the second file has one extra line
- 3a4 means after line 3 line 4 is added
We change file and compare again with the same command
file1
file2
View Verbose Diff
We can list all lines of two files with which lines will add or deleted both files to match each other.
View Verbose Diff
Unified Mode
In a unified view, only one file is shown with related changes like delete or add. It is simpler than verbose mode to review.
Unified Mode
Источник
Сравнение файлов в 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, которая в наглядном виде показывает где и что изменилось в файлах.
Источник
Best Diff Tools to Compare File Contents on Linux
Diff tools are used by countless people all around the world, be it developers, web designers, editors, photographers, engineers, the possibilities are countless. They use these tools to find out the differences between different files, folders, and directories; so that they know which components to change and which not to. Keep on reading to know about the best diff tools to compare your file contents.
1. Diff command
Diff is a simple and easy to use command-line tool used to compare your file or document content. It compares file line by line and print the difference between them. By default, it comes pre-installed in most Linux operating systems.
• Compare files line by line
• Easy to use
• Line by line output of differences
• Compatible with multiple operating systems
Colordiff is a wrapper for diff, which is pretty much the same, except that it shows the differences in colors. It has customizable color schemes and available for most Linux operating systems.
• Colored-syntax highlighting
• Digitally-signed source code
• GPL licensed
• Shows line-by-line differences
• Customizable color schemes
• Ability to paginate the output
• Improved readability
• Promoted for numerous other Linux, UNIX, and BSD distributions and OS (Operating Systems).
• Customizable
• Not broadly portable to systems other than Linux and OpenBSD
2. Wdiff
wdiff is another wrapper for diff which is used to compare files and documents on a word-to-word basis. It is very useful if you want to compare two texts for change words. It works by creating two temporary files, one word per line the use diff command on this files to compare the text.
• Available in many languages
• Under the GNU General Public License
• Display word differences between text files
• It is a free software
• It is a line-oriented program
• ND isn’t extended in the kernel part of the operating system.
3. Vimdiff Command
Compared to diff, vimdiff works in an advanced manner. vimdiff shows the differences between two, three, or four versions of the same file or document.
• Separate windows for each file
• You can have numerous diffs at the same time as they will each be in their tab
• You can change files in vimdiff if you need to
• Mouse-free interface
• Smart visualization
• Lightweight software
• The default algorithm is slow
• Very frequent updates
• If not careful, useless plug-ins will be loaded that clutter the screen
4. Kompare
Kompare a GUI wrapper which lets you find the differences between files while also merging them if needed. It is designed for developers that allow users to compare two different text files or two directories. When you compare two directories, it displays a directory tree for both selected directories.
• Several diff formats
• Comparison of directories
• Ability to personalize the interface
• Create and apply patches to source files
• Mouse-free/only keyboard
• Flexible features
5. DiffMerge
Diffmerge is a software that allows its users to compare and merge files through visual means. It has a two engines, one is a diff engine that shows the difference between two files and a merge engine that displays the changed lines between selected files.
• Cross-platform software
• Graphic representation of the changes between three files
• Configurable
• Windows Explorer/browser integration
• Automatic merging
• Full control over editing
• Able to handle large files well
• Slow start-up time
6. Meld – Diff Tool
Meld is a diff and merge tool, made especially for developers, who need to compare files. It is a lightweight tool and allows you to compare files, directories, and version controlled programs.
• Comparison of two-way and three-way directories and files
• Files comparisons are automatically updated as you type
• Visualizations that make file comparison easier
• Git, Bazaar, Mercurial, Subversion, etc. are supported
• Easy-to-use
• Direct editing of files is supported
• Clean GUI
• Free and open source
• Works fast on Linux
• Availability of Internationalization
• Works slow on larger files
• Failed to work on several file types
• No available option to compare rows horizontally
• Mac version lags a lot to start
• No available context menu integration on Explorer
• Similar lines not aligned
• Extremely slow on comparing folders with sub-folders
• Opens slow on Windows
7. Diffuse – GUI Diff Tool
Diffuse is a free, simple and easy to use diff tool written in Python. It also offers two functionalities file comparison and version control. It also allows file editing, merging and display the difference between selected files.
• Easy keyboard navigation
• Syntax highlighting
• Supports Unicode
• Git, CVS, Darcs, Mercurial, RCS, Subversion, SVK, and Monotone are also supported
• Easy-to-use
• Ability to edit different files directly
• Ability to match lines in adjacent files
• Select lines using a mouse-pointer
• Free software
• No stealth
• Not customizable
• Not portable
8. KDiff3 – – Diff and Merge Tool
KDiff3 is a cross-platform diff and merge tool and works on Linux, macOS and Windows. It is a file and folder merge tool used to compare and merge two to three files and directoires.
• Auto-merge is supported
• Differences are printed
• Windows Explorer/browser integration available
• Unicode is supported
• Three-way merges with a common ancestor are supported
• Manual code aligning is available
• Free software
• Customizable UI
• A built-in editor that is designed to deal with merge-conflicts
• KDE libraries needed to use KDiff3
• Issues with fonts
• Users have to face problems when the number of lines of files is not the same
9. TkDiff
TkDiff is a simple, lightweight and cross-platform GUI wraper for diff tool. It allows you to view the differences between two files side by side.
• Cross-platform software
• Availability of diff bookmarks
• Graphical map of differences
• Three-way merging is supported fully
• Supported by multiple platforms
• Supported by Subversion, Git, Mercurial, and many more
• Syntax highlighting
• Easy-to-use
• Easy and efficient navigation
• Works with plain text documents as well
• Highly configurable
• Lightweight
• Written in Tcl/Tk
10. Visual Studio code
Visual studio code is a code editor made by Microsoft. It supports several development operations like debugging, task running, and version control. It works on Linux, macOS and Windows operating systems.
• Embedded Git control
• No configuration or plug-ins needed before starting to use it
• Runs on any platform
• Customizable
• Excellent performance
• Open-source
• Numerous tutorials and ways for assistance available
• Zero merge functionality
11. Intellij Idea Community Edition
Intellij Idea is an enterprise development, cross-platform software for multiple operating systems. It is used to review the differences between any two files, folders, text sources, or database objects, as well as between local files and their repository versions.
• Well supported for editing Java/Maven projects
• Available in many languages
• Free source (only community edition)
• Lack of framework support
12. Beyond Compare
Beyond compare is a tool for comparing file contents with simplicity and ease. It is a multi-platform and combines file and directory compare functions in single package. It has an ability to compare local, FTP, Dropbox and Amazon S3 directoires.
• Access data from anywhere
• Ability to synchronize folders
• Ability to personalize diff rules
• Ability to edit files directly
• Ability to compare image files
• Ability to compare remote directories
• Rich with features
• Works perfectly with larger files
• Three0way merge supported
• Powerful commands
• Paid propriety software
13. XXdiff – Diff and Merge Tool
XXdiff is yet another diff and merge tool that runs on multiple operating systems. It is a graphical tool used for viewing the difference between two or three files and directories. It uses external diff tools to compute differences.
• Repetitive comparison of two and three files
• Repetitive comparison of two directories
• Free source
• Horizontal difference highlighting available
• Full ability to personalize with a resource file
• Unicode encoded files not supported
14. Git Diff
Diff command is used in git to track the difference between the changes made on a file. This tool takes two inputs and reflects the differences between them. It is not necessary that these inputs are files only. It can be branches, working trees, commits and more.
• Multiple backups available
• Cross-platform
• No extra tools or plug-ins needed
• Easy branching and merging available
• Free source
• Easy-to-use
• Efficient
• A few confusing merging issues
• No native GUI
15. P4Merge
P4Merge is a visual diff tool used to display the differences between file versions. It helps you to resolve conflicts and merge competing versions into one. You can use P4Merge to track and compare the effects of your work free of cost.
Features:
• Compare JPEG, GIF, TIFF, BMP, and other file formats
• Highlight differences on overlaid images
• Extend using the Qt API
• Display line numbers when comparing and merging files
• Ability to visualize your merges
• Able to handle multiple file types
• Cross-platform
• Highly configurable
• Clever auto resolution
• UI can be confusing in the beginning
• Lags on larger files
• Directory composition not supported
16. Sublime Merge
Sublime Merge is a free merge and diff tool used to compare code side-by-side to resolve conflicts before merging changes. It has an ability to search for specific commits, command line integration, code and file history, and syntax highlighting.
• Easily merging
• Availability of two-way and three-way diff
• Built-in support for Mercurial, Git, and Subversion commands
• Changes are highlighted
• Interactive
• Patience diff algorithm
• Scroll Sync
• Clean and readable interface
• Undo and redo available
• Configurability
• No such external tools required
• Only light mode available for evaluation
17. DiffPlug
DiffPlug is another great diff tool that is available on every platform for free. It is used to view, edit and compare files.
• Designed for “correct” behavior
18. Code Compare
Code Compare is a free of cost diff tool to compare and merge files and folders. It shipped as a standalone file diff tool and a Visual Studio extension. It allows you to work with your sources without any additional environments and pre-installations, that provides you higher application performance.
• Integrates with TFS, SVN, Git, Mercurial, and Perforce
• Colored blocks for edited text
• Visual Studio integration
• Filtering options for including or excluding specific file and folder types
• Easily merge through the point and click mechanism with a mouse
• Slow launch time
19. DiffPDF
DiffPDF is a simple and easy to use tool used for comparing two PDF files and let your display the differences. By default, it compares two files by text. It also allows you to compare image and graph.
• Compare text
• View changes
• Exclude Margins
• Set page ranges
• Generate reports
• Free and Open surce
• Words Comparison Mode
• Characters Comparison Mode
• Designed to produce more accurate results
20. Mergely
Mergely is an online document merger and diff making application. It is used for viewing and merging changes between files online. It is a pure Javascript library that helps you to enhance your online CMS system.
• Ability to track your file changes online
• Pure Javascript/HTML5
• Accessibility of a browser-based differencing tool
• Easy-to-use
• Free of cost
• Diff/merge changes in web apps
• No office suites
• Terrible cloud storage
Conclusion
As you can see, there are endless options to choose from, some diff/merge/compare tools are costly while others are completely free, some work on all operating systems while others are only compatible with one. If you are a developer who requires a good-quality, configurable, and easy-to-use diff tool to compare your file contents, we hope our article was able to provide help and maybe clear the confusion if you had any.
We would recommend Diffuse, Meld, KDiff3, and Beyond Compare as some of the best choices.
Источник