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
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.