How to get diff to report summary of new, changed and deleted lines


Unix Problem Overview

I want to have summary of difference between two files. Expected output is count of new, deleted and changed lines. Does diff readily provides such output? If not is there any script/utility available which helps in getting the summary.

Unix Solutions

Solution 1 - Unix

I think you are looking for diffstat. Simply pipe the output of diff -u to diffstat and you should get something like this.

 include/net/bluetooth/l2cap.h |    6 ++++++
 net/bluetooth/l2cap.c         |   18 +++++++++---------
 2 files changed, 15 insertions(+), 9 deletions(-)

Solution 2 - Unix

For those using Git or Mercurial, a quick way to see such a summary of ones unstaged changes:

git diff --stat
hg diff --stat

Solution 3 - Unix

If you use diff -u it will generate a unified diff that has lines preceded with + and -. If you pipe that output through grep (to get only the + or -) and then to wc you get the counts for the + es and the - es respectively.

Solution 4 - Unix

Here is the script by suyasha all formatted correctly with line breaks, with some added message output. Good job, suyasha, should have posted your reply as an answer. I would have voted for that.

# USAGE: [file1] [file2]

if [ ! $2 ]
   printf "\n   USAGE: [file1] [file2]\n\n"

diff -u -s "$1" "$2" > "/tmp/diff_tmp" 
add_lines=`cat "/tmp/diff_tmp" | grep ^+ | wc -l`
del_lines=`cat "/tmp/diff_tmp" | grep ^- | wc -l` 
# igonre diff header (those starting with @@) 
at_lines=`cat "/tmp/diff_tmp" | grep ^@ | wc -l`
chg_lines=`cat "/tmp/diff_tmp" | wc -l`
chg_lines=`expr $chg_lines - $add_lines - $del_lines - $at_lines` 
# subtract header lines from count (those starting with +++ & ---) 
add_lines=`expr $add_lines - 1`
del_lines=`expr $del_lines - 1`
total_change=`expr $chg_lines + $add_lines + $del_lines`
rm /tmp/diff_tmp

printf "Total added lines:  "
printf "%10s\n" "$add_lines"
printf "Total deleted lines:"
printf "%10s\n" "$del_lines"
printf "Modified lines:     "
printf "%10s\n" "$chg_lines"
printf "Total changes:      "
printf "%10s\n" "$total_change"


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsuyashaView Question on Stackoverflow
Solution 1 - UnixsigjuiceView Answer on Stackoverflow
Solution 2 - UnixstefanoView Answer on Stackoverflow
Solution 3 - UnixlotharView Answer on Stackoverflow
Solution 4 - UnixBill-GView Answer on Stackoverflow