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

前端 未结 4 1374
醉酒成梦
醉酒成梦 2021-02-06 20:39

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 s

相关标签:
4条回答
  • 2021-02-06 21:08

    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.

    0 讨论(0)
  • 2021-02-06 21:16

    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"
    
    0 讨论(0)
  • 2021-02-06 21:20

    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(-)
    
    0 讨论(0)
  • For those using Git or Mercurial, a quick way to see such a summary of ones unstaged changes:

    git diff --stat
    hg diff --stat
    
    0 讨论(0)
提交回复
热议问题