On Windows 11 (and 10), the File Compare (fc) is a command-line tool that comes part of the system, and it allows you to compare two similar files to determine how they changed over time. Usually, «fc» will be helpful for comparing simple text files, determining the changes made to a script, detecting if a file has been modified, and similar scenarios.
The tool can compare two similar files or the newest version against all the other files in the same location. Also, it includes options to examine the changes at the text level, or in Unicode, ASCII, or binary mode.
In this how-to guide, you will learn steps to use the tool to compare files with Command Prompt on Windows 11 as well as on Windows 10.
Recent updates
This guide has been updated to ensure the instructions are still accurate and reflect you can also use the tool on Windows 11.
How to compare files with the fc command on Windows 11
To compare files with the fc command tool, use these steps:
- Open Start.
- Search for Command Prompt, right-click the top result, and select the Run as administrator option.
- Type the following command to browse to the folder with the files you want to compare and press Enter: cd PATH\TO\FILES
In the command, update the path with the location of the folder with the files to compare. This example navigates to the Downloads folder: cd C:\Users\USERACCOUNT\Downloads
- Type the following command to compare two similar files and press Enter: fc filename1.txt filename2.txt
In the command, replace filename1.txt and filename2.txt for the name of the files you want to compare.
- Type the following command to compare two similar files in ASCII mode and press Enter: fc /L filename1.txt filename2.txt
- Type the following command to compare two files displaying only the first line that is different and press Enter: fc /a filename1.txt filename2.txt
- Type the following command to compare two files in Unicode mode and press Enter: fc /u filename1.txt filename2.txt
- Type the following command to compare two files in binary mode and press Enter: fc /b filename1.txt filename2.txt
- Type the following command to compare all the files (*.txt) in the same folder to the new file (filename2.txt) and press Enter: fc *.txt filename2.txt
- Type the following command to compare two files in different locations and press Enter: fc DRIVE:\PATH\TO\filename1.txt DRIVE:\PATH\TO\filename2.txt
In the command, replace DRIVE for the storage location drive letter and \PATH\TO\filename1.txt and \PATH\TO\filename2.txt with the path and name of the files you want to compare.This example compares two files in different folders: fc C:\Users\USERACCOUNT\Downloads\filename1.txt C:\Users\USERACCOUNT\Downloads\new\filename2.txt
All the latest news, reviews, and guides for Windows and Xbox diehards.
- Confirm the output to see the difference between the files.
- Quick tip: You can view the list of options and more examples using the fc /? command.
Once you complete the steps, you will be able to see the difference between two similar files.
While the tool allows you to compare files, remember that this is a basic tool meant to be used with text files and extensions like .exe, .com, .sys, .obj, .lib, or .bin. You may be able to compare files like those from Microsoft Office or images, but you can only compare them at the binary level.
More resources
For more in-depth insights, troubleshooting tips, and the latest updates on Windows 11 and 10, be sure to explore these resources:
- Windows 11 on Windows Central — All you need to know
- Windows 10 on Windows Central — All you need to know
Mauro Huculak has been a Windows How-To Expert contributor for WindowsCentral.com for nearly a decade and has over 15 years of experience writing comprehensive guides. He also has an IT background and has achieved different professional certifications from Microsoft, Cisco, VMware, and CompTIA. He has been recognized as a Microsoft MVP for many years.
Meld
Being free and open source, Meld is a very popular tool on Windows (it’s also available for Linux). It supports three-way comparing and merging and lets you edit files directly from the comparison view. Apart from diffing files, Meld also supports comparison of folders.
Beyond Compare
The Beyond Compare team makes a fine diff tool for Windows (as well as macOS and Linux, by the way). It goes well beyond (pun intended) diffing simple text and also allows comparing PDF, Excel and image files. The «Pro» version also includes a solid three-way merge.
Araxis Merge
Just like Beyond Compare, Araxis Merge supports more than just text and image files. It also lets you compare office documents (like MS Word, Excel, Powerpoint, or ODF). It comes in standard and professional editions, and for people working on both Windows and macOS, it’s good to know that a single license is valid for both platforms.
KDiff3
Another free and open source tool answers to the name of KDiff3. The project hasn’t seen many updates in recent years (though you may be able to find more recent releases through this page), but it remains a solid diff and merge tool that should satisfy basic needs.
Get the Git Cheat Sheet
Download one of the web’s most popular resources on Git! It’s free!
DeltaWalker
Much like Araxis, the DeltaWalker diff tool also lets you compare office files. However, it goes one step further by letting you compare file archives like ZIP, JAR, and TAR files.
If you’re regularly performing comparisons on a folder basis, it’s good to know that DeltaWalker shines with great performance in this area. DeltaWalker supports Windows, macOS and Linux.
P4Merge
Perforce, the company best known for its enterprise version control platform, also offers a solid diff tool: P4Merge is free of charge and comes with a basic feature set that makes it an interesting option on Windows, macOS and Linux.
Code Compare
Besides offering all the standard diff and merge capabilities, Code Compare comes with some special features like syntax highlighting, semantic code comparison and a VisualStudio integration.
The basic version can be used free of charge, while the Professional Edition delivers the full feature set.
WinMerge
WinMerge is an open-source diff tool with some nice features like folder and image comparison, and three-way file comparison.
Guiffy
Guiffy is a full-featured tool with syntax highlighting, three-way comparisons and merges, and multiple comparison algorithms. It comes in pro and expert versions, and supports Windows, macOS and Linux.
Integrations
Another aspect to watch out for is integrations: before choosing your favorite tool, you should make sure that it plays nicely with the rest of your tool chain. I can already confirm that most of the mentioned tools work seamlessly with Tower, our own Git client.
If you don’t need the power of a dedicated Diff tool application, the integrated diff views in Tower might even be sufficient for you:
See for yourself and try it 30 days for free.
Conclusion
Diff & merge apps are amongst the most underestimated tools. But a good one can be really helpful in a lot of situations. Try one of the above and see for yourself!
Get the Git Cheat Sheet
Download one of the web’s most popular resources on Git! It’s free!
Веб-мастерам или владельцам сайтов часто бывает необходимо сравнить два файла по содержимому. Из этой статьи вы узнаете как сравнить два файла между собой. Здесь описаны все известные мне способы для сравнения текстовых файлов и скрипты (html, css, php и так далее).
Meld — графический инструмент для получения различий и слияния двух файлов, двух каталогов. Meld — визуальный инструмент сравнения и объединения файлов и каталогов для Linux. Meld ориентирован, в первую очередь, для разработчиков. Однако он может оказаться полезным любому пользователю, нуждающемуся в хорошем инструменте для сравнения файлов и директорий.
В Meld вы можете сравнивать два или три файла, либо два или три каталога. Вы можете просматривать рабочую копию из популярных систем контроля версий, таких, таких как CVS, Subversion, Bazaar-NG и Mercurial. Meld представлен для большинства linux дистрибутивов (Ubuntu, Suse, Fedora и др.), и присутствует в их основных репозиториях.
# apt install meld
Meld существует и под Windows, но я не рекомендую его использовать в этой операционной системе.
Бесплатная программа WinMerge позволяет сравнивать не только содержимое файлов, она также сравнивает содержимое целых папок. WinMerge является Open Source инструментом сравнения и слияния для Windows. WinMerge может сравнивать как файлы, так и папки, отображая различия в визуальной текстовой форме, которые легко понять и обработать.
После установки, открываете пункт меню «Файл» — «Открыть». Выбираете файлы для сравнения. Для этого нажимаете на кнопку «Обзор» и выбираете файл. Выбрав файлы, нажимаете на кнопку «ОК».
В WinMerge можно также редактировать файлы. После закрытия окна сравнения, программа предложит сохранить изменения в файлах.
diff — утилита сравнения файлов, выводящая разницу между двумя файлами.
Kompare — отображает различия между файлами. Умеет сравнивать содержимое файлов или каталогов, а также создавать, показывать и применять файлы патчей. Kompare — это графическая утилита для работы с diff, которая позволяет находить отличия в файлах, а также объединять их. Написана на Qt и рассчитана в первую очередь на KDE. Вот ее основные особенности:
Способ 5. Сравнение файлов в программе Total Commander
В Total Commander существует инструмент сравнения файлов по содержимому, где можно не только сравнить содержимое, но и редактировать его и копировать из одного файла в другой.
После запуска Total Commander – в одной из панелей выбираете (клавиша Insert) первый файл для сравнения – во второй панели открываете папку со вторым файлом и ставим на него курсор. Вызываем программу для сравнения: «Файлы→Сравнить по содержимому».
Для внесения изменений в файл достаточно нажать на кнопку «Редактировать». В программе доступны функции копирования и отката, поиска и изменение кодировки. Если вы внесли изменения в файл, то после закрытия окна сравнения, будет предложено сохранить изменения.
Notepad++ не умеет сравнивать файлы. Для появления этого функционала в Notepad++ нужно установить плагин «Compare».
Запускаете редактор – переходите в пункт меню «Плагины» — «Plugin Manager» — «Show Plugin Manager». В новом окне выбираете плагин «Compare» и жмёте кнопку «Install».
После установки плагина откройте два файла и выбирите меню «Плагины» — «Compare» — «Compare (Alt+D)». Результат сравнения файлов будет представлен в отдельных панелях. Напротив строк, в которых найдены отличия будет стоять предупреждающий знак.
Способ 7. Сравнение файлов с помощью командной строки Windows
Сравнение с помощью командной строки Windows (cmd.exe) не позволяет редактировать файлы, но просто сравнить содержимое файлов, используя этот способ, вы можете.
Для вызова командной строки Windows перейдите «Пуск» — «Все программы» — «Стандартные» — «Командная строка» или нажмите клавиш «Windows+R», введите cmd и нажмите клавишу Enter.
В командной строке введите команду:
fc /N путь к первому файлу путь ко второму файлу
Unix утилита comm входит в стандартную поставку всех Unix- дистрибутивов, таких как FreeBSD, GNU/Linux (пакет GNU Coreutils) и другие.
Программа comm используется для построчного сравнения двух текстовых файлов с отсортированными по алфавиту строками, в соответствии с используемой локалью. Для сортировки можно использовать утилиту sort.
При вызове без параметров рассматриваемая утилита будет выводить строки в трех столбцах: первый столбец будет содержать строки, присутствующие лишь в файле 1, второй столбец — строки, присутствующие лишь в файле 2, а третий столбец — строки, присутствующие в обоих файлах. Утилита поддерживает параметры -1, -2 и -3, позволяющие не выводить столбцы под соответствующими номерами. Статус завершения работы утилиты не зависит от результата распределения строк по столбцам; в случае успешного распределения строк утилита завершает работу с нулевым статусом, в случае возникновения любой ошибки — с ненулевым.
Базовый синтаксис команды выглядит следующим образом:
$ comm [параметры] <файл 1> <файл 2>
Параметры запуска: -1 Подавить вывод первой колонки; -2 Подавить вывод второй колонки; -3 Подавить вывод третьей; -i Нечувствительное к регистру сравнение строк.
Примеры запуска утилиты comm для сравнения двух файлов по содержимому:
-
comm -1 file1 file2 сравнить содержимое двух файлов, не отображая строки принадлежащие файлу ‘file1’
-
comm -2 file1 file2 сравнить содержимое двух файлов, не отображая строки принадлежащие файлу ‘file2’
-
comm -3 file1 file2 сравнить содержимое двух файлов, удаляя строки встречающиеся в обоих файлах
-
запуск comm с предварительной сортировкой
comm <(sort file1.txt) <(sort file2.txt)
-
В текстовых файлах часто встречаются нежелательные символы, такие как символ возврата каретки, символ конца строки в стиле Windows, символов пробела или табуляции. Самым надежным вариантом было бы отфильтровать все такие нежелательные символы, а поскольку данные являются строго числовыми, это довольно легко сделать, например, с помощью sed (пример вырезания нежелательных символов
sed 's/[^0-9]//g' < input > output
. В итоге получаем такую команду:
comm <(sed 's/[^0-9]//g' file1.txt | sort) <(sed 's/[^0-9]//g' file2.txt | sort)
Помимо локальных программ и утилит, существуют удобные онлайн-сервисы для сравнения файлов:
Система контроля версий Git предоставляет мощные инструменты для сравнения файлов:
git diff file1.txt file2.txt
Эта команда покажет различия между двумя файлами в формате патча. Для более удобного визуального сравнения можно использовать графический интерфейс:
git difftool file1.txt file2.txt
-
Предварительная подготовка: Перед сравнением убедитесь, что файлы имеют одинаковую кодировку и формат переноса строк.
-
Игнорирование пробелов: Многие инструменты позволяют игнорировать различия в пробелах и табуляции, что полезно при сравнении кода.
-
Сравнение больших файлов: Для объемных файлов используйте инструменты с поддержкой построчного сравнения, чтобы снизить нагрузку на систему.
-
Безопасность: При использовании онлайн-сервисов для сравнения конфиденциальных данных убедитесь в их надежности и политике конфиденциальности.
Сравнение файлов по содержимому — важный навык для веб-мастеров, разработчиков и системных администраторов. В этой статье мы рассмотрели самые эффективные способы выполнения этой задачи как в Windows, так и в Linux. От графических инструментов, таких как Meld и WinMerge, до командных утилит вроде diff и comm — каждый метод имеет свои преимущества.
Выбор конкретного инструмента зависит от ваших потребностей, операционной системы и предпочтений в интерфейсе. Графические решения, как правило, более удобны для визуального сравнения и редактирования, в то время как командные утилиты отлично подходят для автоматизации и работы с большими объемами данных.
Регулярная практика использования этих инструментов поможет вам быстро находить различия между файлами, что особенно полезно при отладке кода, сравнении версий документов или проверке целостности данных. Независимо от выбранного метода, владение навыками сравнения файлов значительно повысит вашу продуктивность в работе с цифровым контентом
There are times when you need to compare two files and check whether their content is different. In some situations, you could just open the two files and look through their contents, like when you want to compare two pictures or two text files. However, that’s a rather tedious task to perform, and you might miss small differences, like a slight change in tint on a photo, or a phrase in a text file. That’s why it is good to know a few methods to programmatically compare the contents of two files, using software instead of your senses. 🙂 Here are three ways in which you can do that, using PowerShell or third-party apps for Windows:
How to compare two files using PowerShell
Windows 10 doesn’t have a built-in tool for comparing two files. However, you can use PowerShell to do so. Start by opening PowerShell: a quick way to do it is to press the Win + X keys on your keyboard simultaneously, and then press I if you want to run PowerShell as a standard user, or A if you want to run it as an administrator.
Once you’ve opened PowerShell run the following command:
if((Get-FileHash «Path to the first file»).hash -eq (Get-FileHash «Path to the second file»).hash) {«The two compared files are identical»} else {«The two compared files are NOT identical»}
Of course, you should change «Path to the first file» and «Path to the second file» with the real paths to your files. For example, we wanted to compare two files called DigitalCitizen1.txt and DigitalCitizen2.txt, both found on our D: drive.
To compare their contents, we had to run this command:
if((Get-FileHash «D:DigitalCitizen1.txt»).hash -eq (Get-FileHash «D:DigitalCitizen2.txt»).hash) {«The two compared files are identical»} else {«The two compared files are NOT identical»}
If the content of the two files is the same, the output you get in PowerShell tells you that «The two compared files are identical.»
If the contents of the two files are different, the output you get in PowerShell tells you that «The two compared files are NOT identical.»
Although using PowerShell is both fast and fairly easy, some people do not like using command-line environments. Because of that, we’re also going to show you how to compare two files in Windows using third-party apps that offer graphical user interfaces.
How to compare two files using Total Commander
Total Commander is a shareware file manager that is available for all Windows versions. You can get it from its official website, here: Total Commander. Once you’ve installed and opened it, use its windows to navigate to the two files that you want to compare. In the left side of Total Commander, navigate to the first file, and on the right, navigate to the second file. Then, select the two files by clicking on them and then pressing the spacebar. When the files are selected, their name is colored in red, as you can see in the screenshot below.
Now open the Files options from Total Commander’s menu, on the top-left corner, and click on «Compare By Content.«
If the two files that you chose to compare are identical, Total Commander opens a small popup window in which it tells you that «The two files have the same content!».
If the contents of the two compared files differ, Total Commander opens a window in which it shows you the differences between the two files, highlighted in red.
Total Commander also gives you other options for checking the differences and editing the two files, but they are out of the scope of this tutorial, so we’re letting you discover them on your own.
How to compare two files using AptDiff
A freeware app that can help you compare files by contents is AptDiff. Although the app is not maintained anymore, it still works in all Windows versions from Windows 2000 and up, including Windows 10. You can get it from Softpedia.
After you install and open AptDiff, it immediately asks you to select the files that you want to compare. Enter the paths to the two files or use the «…» buttons to browse through your computer and select them.
Then choose whether you want to compare the two files as text files, or if you prefer to compare them on a binary level. You can choose any option, regardless of the type of files that you compare. However, know that once the contents of the files are compared, the app loads their contents in two separate panes and shows you the differences identified, if any. If you choose to «Compare as Text,» the two panes show the text contents and differences. Otherwise, if you choose to «Compare as Binary,» the contents of the two files are shown in hexadecimal code.
Just like Total Commander, AptDiff also lets you use additional tools for comparing and editing the contents of the two files.
What is your favorite way of comparing two files by content?
Now you know three easy ways of comparing two files by content in Windows. Which of them is your favorite? Do you prefer using commands in PowerShell, or would you rather install and use a third-party app that also has a visual interface? If you know other methods to compare files, let us know by leaving a comment in the section below.