Wednesday, December 16, 2009

Find and Diff Only Certain Files in One Directory Structure to Another

If you want to compare a directory structure only containing files and directories to change/overlay atop another, it is useful to have a tool to compare only the files (and perhaps only certain ones) from that one directory structure to the other directory structure you wish to overlay those files atop of.

I started using a similar method a few years ago, and thought I'd already noted it, but maybe I forgot. Anyway, hope the bash script helps:


# Written by Gary S. Weaver

set -e


if [ $# -ne 3 ]; then
  echo "usage: dir1 dir2 expression"
  exit 1

# canonicalize and set as variables
d1c=`cd -P -- "$(dirname -- "$d1")" && printf '%s\n' "$(pwd -P)/$(basename -- "$d1")"`
d2c=`cd -P -- "$(dirname -- "$d2")" && printf '%s\n' "$(pwd -P)/$(basename -- "$d2")"`

set -x verbose
cd "${d1}"
find . -name "${exp}" -exec echo "Comparing \"${d1c}/{}\" to \"${d2c}/{}\" ..." \; -exec diff "{}" "${d2c}/{}" \;
Put that file on the path (I called mine "diffo") and chmod +x it. Then use it like:
diffo dir1 dir2 "*"
diffo dir1 dir2 *.java
which will only compare those files found in dir1 to dir2 (not the same as diff -r. diff -r also compares dir2 to dir1).

Tips and tricks:
* Add --side-by-side option before the last \; and get a side by side diff.
* For those using OS X, TextWrangler is free and you can do twdiff on files that are different to easily merge changes (click on difference at bottom and use the apply button).

Note: the line to canonicalize was based on the "canonicalize" bash script by Jesse Wilson.

No comments: