问题
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.
回答1:
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.
回答2:
I think you are looking for diffstat. Simply pipe the output of diff
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(-)
回答3:
For those using Git or Mercurial, a quick way to see such a summary of ones unstaged changes:
git diff --stat
hg diff --stat
回答4:
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.
#!/bin/bash
# USAGE: diffstat.sh [file1] [file2]
if [ ! $2 ]
then
printf "\n USAGE: diffstat.sh [file1] [file2]\n\n"
exit
fi
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"
来源:https://stackoverflow.com/questions/767198/how-to-get-diff-to-report-summary-of-new-changed-and-deleted-lines