Linux compare two folders

How to Find Difference Between Two Directories Using Diff and Meld Tools

In an earlier article, we reviewed 9 best file comparison and difference (Diff) tools for Linux and in this article, we will describe how to find the difference between two directories in Linux.

Normally, to compare two files in Linux, we use the diff – a simple and original Unix command-line tool that shows you the difference between two computer files; compares files line by line and it is easy to use, comes with pre-installed on most if not all Linux distributions.

The question is how do we get the difference between two directories in Linux? Here, we want to know what files/subdirectories are common in the two directories, those that are present in one directory but not in the other.

The conventional syntax for running diff is as follows:

By default, its output is ordered alphabetically by file/subdirectory name as shown in the screenshot below. In this command, the -q switch tells diff to report only when files differ.

Difference Between Two Directories

Again diff doesn’t go into the subdirectories, but we can use the -r switch to read the subdirectories as well like this.

Using Meld Visual Diff and Merge Tool

There is a cool graphical option called meld (a visual diff and merge tool for the GNOME Desktop) for those who enjoy using the mouse, you can install it as follows.

Once you have installed it, search for “meld” in the Ubuntu Dash or Linux Mint Menu, in Activities Overview in Fedora or CentOS desktop and launch it.

You will see the Meld interface below, where you can choose file or directory comparison as well as version control view. Click on directory comparison and move to the next interface.

Meld Comparison Tool

Select the directories you want to compare, note that you can add a third directory by checking the option “3-way Comparison”.

Select Comparison Directories

Once you selected the directories, click on “Compare”.

Listing Difference Between Directories

In this article, we described how to find the difference between two directories in Linux. If you know any other commandline or gui way don’t forget to share your thoughts to this article via the comment section below.

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.

Читайте также:  Как отключить проверку подписи драйверов при установке windows

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.

Источник

Разница между двумя каталогами в Linux

Я пытаюсь найти файлы, существующие в одном каталоге, но не в другом, я попытался использовать эту команду:

проблема с вышеуказанной командой в том, что она находит оба файла в dir1 а не dir2 а также файлы dir2 а не dir1 ,

Я пытаюсь найти файлы dir1 а не dir2 только.

вот небольшой пример того, как выглядят мои данные

другой вопрос на мой взгляд, как я могу найти файлы в dir1 а не dir2 или dir3 в одной команде?

14 ответов

пояснение:

diff -r dir1 dir2 показывает, какие файлы находятся только в dir1 и только в dir2, а также изменения файлов, присутствующих в обоих каталогах, если таковые имеются.

diff -r dir1 dir2 | grep dir1 показывает, какие файлы находятся только в dir1

awk для печати только имени файла.

Это должно сделать работу:

параметры объяснены (через diff (1) man page):

  • -r — рекурсивно сравните все найденные подкаталоги.
  • -q — вывод только в том случае, если файлы отличаются.

эта команда даст вам файлы, которые находятся в dir1 и не в директория dir2.

о знак, вы можете Google это, как подмена процесса.

хороший способ сделать это сравнение, чтобы использовать find С md5sum , потом diff .

использовать find чтобы перечислить все файлы в каталоге, вычислите хэш md5 для каждого файла и передайте его в файл:

выполните ту же процедуру в другом каталоге:

затем сравните результат двух файлов с «diff»:

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

еще один хороший способ сделать эту работу-использовать git

С наилучшими пожеланиями!

Meld (http://meldmerge.org/) делает большую работу по сравнению каталогов и файлов внутри.

vim DirDiff плагин-еще один очень полезный инструмент для сравнения каталогов.

он не только перечисляет, какие файлы отличаются между каталогами, но также позволяет проверять/изменять с помощью vimdiff файлы, которые отличаются.

другой (возможно, более быстрый для больших каталогов) подход:

на sed команда удаляет первый компонент каталога благодаря)

Это немного поздно, но может кому-то помочь. Не уверен, что diff или rsync выплевывают только имена файлов в голом формате, как это. Спасибо plhn за предоставление этого приятного решения, которое я расширил ниже.

Если вы хотите только имена файлов, так что легко просто скопировать файлы, необходимые в чистом формате, вы можете использовать команду find.

предполагается, что dir1 и dir2 находятся в одной родительской папке. СЭД просто удаляет родительскую папку, чтобы вы могли сравнить яблоки с яблоками. Последний sed просто возвращает имя dir1.

Если вы просто хотите файлов:

аналогично для каталогов:

в принятом ответе также будут перечислены файлы, которые существуют в обоих каталогах, но имеют разное содержимое. Чтобы перечислить только файлы, существующие в dir1, вы можете использовать:

  • diff-r dir1 dir2: сравнить
  • grep ‘Only in’: получить строки, содержащие ‘Only in’
  • grep dir1: получить строки, содержащие dir
Читайте также:  Обои kali linux 1920 1080

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

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

или если вы хотите видеть только файлы из первого каталога:

P. S. Если вам нужно сравнить размеры файлов и файлов хэши для потенциальных изменений, я опубликовал обновленный скрипт здесь: https://gist.github.com/amakukha/f489cbde2afd32817f8e866cf4abe779

упрощенный способ сравнения 2 каталогов с помощью команды DIFF

diff имя файла.1 именем.2 > имя_файла.dat > > Enter

открыть именем.dat после завершения запуска

и вы увидите: Только в имени файла.1: имя.Два Только в: directory_name: name_of_file1 Только в: directory_Name: name_of_file2

kdiff3 имеет приятный интерфейс diff для файлов и каталогов.

Он работает под Windows & Linux.

GNU grep может инвертировать поиск с помощью опции -v . Это делает grep отчет о строках, которые не совпадают. С помощью этого вы можете удалить файлы в dir2 из списка файлов в dir1 .

опции -F -x рассказать grep для выполнения строкового поиска по всей строке.

это скрипт bash для печати команд для синхронизации двух каталогов

Источник

Compare files in two different directories in Linux

A shell script which shows differences in multiple files in two different directories and also possibly create an output file including where all mismatches were found.

File dir1/file1 compare only with dir2/file1 (similarly for other files — file2 compare with file2)

If any changes found: status should be «Miss-match FOUND in file file1 for example» and same thing should do for all other files as well and write a all of the results into a one file

Thanks in advance

2 Answers 2

Use the diff command. Using the -r flag you can compare folders recursively:

The output will be in a format which the patch command understands. You can save it in a file and apply those changes to dir1 using

If you deal with text files and want to just see the differences, I would customize the diff output, as hek2mgl suggested. But if you want more control, for example to execute some commands after finding different files or you must compare binary files, you may utilize find and cmp .
Below is the sample, which you may customize:

Depending on your situation (if filenames do not contain spaces, there are no missing files, etc.) you may omit some parts — this was just tailored from a larger script.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!
  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Источник

Читайте также:  Play on linux gecko

How do you compare two folders and copy the difference to a third folder?

You’ve got three folders:

  • folder current, which contains your current files
  • folder old, which contains an older version of the same files
  • folder difference, which is just an empty folder

How do you compare old with current and copy the files which are different (or entirely new) in current to difference?

I have searched all around and it seems like a simple thing to tackle, but I can’t get it to work in my particular example. Most sources suggested the use of rsync so I ended up with the following command:

What this does however, is copies all the files from new to difference, even those which are the same as in old.

In case it helps (maybe the command is fine and the fault lies elsewhere), this is how I tested this:

  1. I made the three folders.
  2. I made several text files with different contents in old.
  3. I copied the files from old to new.
  4. I changed the contents of some of the files in new and added a few additional files.
  5. I ran the above command and checked the results in difference.

I have been looking for a solution for the past couple of days and I’d really appreciate some help. It doesn’t necessarily have to be using rsync, but I’d like to know what I’m doing wrong if possible.

Источник

Comparing the contents of two directories

I have two directories that should contain the same files and have the same directory structure.

I think that something is missing in one of these directories.

Using the bash shell, is there a way to compare my directories and see if one of them is missing files that are present in the other?

14 Answers 14

You can use the diff command just as you would use it for files:

If you want to see subfolders and -files too, you can use the -r option:

A good way to do this comparison is to use find with md5sum , then a diff .

Example

Use find to list all the files in the directory then calculate the md5 hash for each file and pipe it sorted by filename to a file:

Do the same procedure to the another directory:

Then compare the result two files with diff :

Or as a single command using process substitution:

If you want to see only the changes:

The cut command prints only the hash (first field) to be compared by diff. Otherwise diff will print every line as the directory paths differ even when the hash is the same.

But you won’t know which file changed.

For that, you can try something like

This strategy is very useful when the two directories to be compared are not in the same machine and you need to make sure that the files are equal in both directories.

Another good way to do the job is using Git’s diff command (may cause problems when files has different permissions -> every file is listed in output then):

Источник

Оцените статью