简体   繁体   中英

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.

Condition

  1. File dir1/file1 compare only with dir2/file1 (similarly for other files - file2 compare with file2)

  2. 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

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

diff -ur dir1 dir2

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

diff -ur dir1 dir2 > my.patch
cd dir1
patch -p1 < ../my.patch

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:

#!/bin/bash
IFS_SAVE="$IFS"
IFS=$'\x0a'

for f in $(find dir1 -type f -printf "%f\n"); do {
    f1="dir1/$f"
    f2="dir2/$f"
    cmp --quiet "$f1" "$f2"
    check=$?
    if [ $check -eq 0 ] ; then
        echo -e "OK: $f"
    elif [ $check -eq 1 ] ; then
        echo -en "Mismatch FOUND in files: "
        filesize1=$(stat --printf="%s" "$f1" )
        filesize2=$(stat --printf="%s" "$f2" )
        echo "$f1" size:"$filesize1" "$f2" size:"$filesize2" check:"$check" 
        #you may put diff ... or anything else here
    else 
        echo "cannot compare files, probably $f2 is missing"
    fi
} ; done
IFS="$IFS_SAVE"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM