- How To Compare Two Text Files Using Linux
- Test and see if your files have updated or changed
- What To Know
- Create the Files to Compare
- Create the First File
- Create the Second File
- How to Compare Two Files Using Linux
- How to Only Show If the Files Are Different
- How to Show a Message If the Files Are the Same
- How to Produce the Differences Side by Side
- Restrict Column Width
- How to Ignore Case Differences When Comparing Files
- How to Ignore Trailing White Space at the End of a Line
- How to Ignore All White Space Differences Between Two Files
- How to Ignore Blank Lines When Comparing Two Files
- Summary
- Сравнение файлов в Linux
- Сравнение файлов diff
- Сравнение файлов Linux с помощью GUI
- 1. Kompare
- 2. Meld
- 3. Diffuse
- 4. KDiff3
- 5. TkDiff
- Выводы
- 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
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.
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.
Источник
Сравнение файлов в 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 или даже сравнить каталоги. Кроме того, есть поддержка слияния и ручного выравнивания.
5. TkDiff
Это очень простая утилита для сравнения файлов написанная на основе библиотеки tk. Она позволяет сравнивать только два файла, поддерживает поиск и редактирование сравниваемых файлов.
Выводы
В этой статье мы рассмотрели как выполняется сравнение файлов linux с помощью терминала, как создавать патчи, а также сделали небольшой обзор лучших графических утилит для сравнения файлов. А какие инструменты для сравнения используете вы? Напишите в комментариях!
Источник
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.
Источник