Git diff with line numbers (Git log with line numbers)

后端 未结 9 877
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 18:57

When I do a git diff or a git log -p, how do I get line numbers of the source file(s) inlined with the output?

I tried to look it up

9条回答
  •  盖世英雄少女心
    2020-11-29 19:21

    Here's two more solutions, expanding on Andy Talkowski's code.

    Plain text:

      git diff | gawk 'match($0,"^@@ -([0-9]+),[0-9]+ [+]([0-9]+),[0-9]+ @@",a){left=a[1];right=a[2];next};\
       /^(---|\+\+\+|[^-+ ])/{print;next};\
       {line=substr($0,2)};\
       /^-/{print "-" left++ ":" line;next};\
       /^[+]/{print "+" right++ ":" line;next};\
       {print "(" left++ "," right++ "):"line}'
    

    Colored text, assuming \033[66m is the format for color codes:

      git diff --color=always | \
        gawk '{bare=$0;gsub("\033[[][0-9]*m","",bare)};\
          match(bare,"^@@ -([0-9]+),[0-9]+ [+]([0-9]+),[0-9]+ @@",a){left=a[1];right=a[2];next};\
          bare ~ /^(---|\+\+\+|[^-+ ])/{print;next};\
          {line=gensub("^(\033[[][0-9]*m)?(.)","\\2\\1",1,$0)};\
          bare~/^-/{print "-"left++ ":" line;next};\
          bare~/^[+]/{print "+"right++ ":" line;next};\
          {print "("left++","right++"):"line;next}'
    

    The code changes lines that start with - and + to -1:- and +1:+, respectively, and lines that start with nothing to (5,6):. The numbers are the line numbers from the respective file.

提交回复
热议问题