Thursday, February 22, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  17] [ 0]  / answers: 1 / hits: 103465  / 2 Years ago, sat, march 19, 2022, 5:05:19

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]


More From » 10.04

 Answers
1

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##*/}"
done


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.


[#39933] Sunday, March 20, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dileble

Total Points: 169
Total Questions: 105
Total Answers: 141

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;