Ubuntu – How to diff multiple files across directories


I am trying to find diffs between all files of same names across two copies of a directory (say a working and a backup). For example, I can diff two files of same name in both:

> diff d1/f.cpp d2/f.cpp

or I can find differences across the directories:

> diff d1 d2

but how can I find differences between the *.cpp files only?

> diff d1/*.cpp d2/*.cpp

does not seem to work (for obvious reasons).

[It is probably easy to solve with loops, but I am trying to find a more elegant way]

Best Answer

You can use a shell loop that runs diff for each file, though this will not catch the cases where d2 contains a file, but d1 doesn't. It might be sufficient though.

for file in d1/*.cpp; do
    diff "$file" "d2/${file##*/}"

Or all on one line:

for file in d1/*.cpp; do diff "$file" "d2/${file##*/}"; done

The ${file##*/} part is a special parameter expansion.

If the file variable contains d1/hello.cpp, then "${file##*/}" will expand to hello.cpp (the value of file, but with everything up to, and including, the last / removed).

So "d2/${file##*/}" will result in d2/hello.cpp and the resulting diff command is thus diff d1/hello.cpp d2/hello.cpp

See http://mywiki.wooledge.org/BashFAQ/100 for more on string manipulations in bash.

On a side note, a version control system (such as subversion, git, mercurial etc...) would make this type of diffing much easier.