Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out changed line numbers from git diff

I need to know the changed line numbers between two commits (HEAD~1 and HEAD) to a repo

git diff HEAD~1 HEAD

returns information in a confusing diff format

I was able to identify newly added files or deleted files by looking at their markers in git diff (ie --- /dev/null and +++/dev/null meaning added, deleted)

Is it possible to identify the lines numbers in the modified files

The need for me is

path/to/file/MyClass1.java
23-56
59-60
72-74

path/to/file/MyClass2.java
1-34
54-56

23-56 , 72-74 and 59-60 are the line/range of lines (denoted as line number) changed between HEAD~1 and HEAD

PS: few of the leads which I found on other SO questions seems to be outdated Any help will be deeply appreciated!

like image 278
anon-sAI Avatar asked May 23 '26 11:05

anon-sAI


1 Answers

This should give the diff for modified files between the two revisions HEAD~1 and HEAD

git diff --unified=0 --diff-filter=M HEAD~1 HEAD 

Using grep utility, the modified lines and index can be removed from the output

git diff --unified=0 --diff-filter=M HEAD~1 HEAD  | grep -v -e '^[+-]' -e '^index'

The output :

diff --git a/some/file b/some/file
@@ -startline1,count1 +startline2,count2 @@
...

On further processing using sed utility, the final command is :

git diff --unified=0 --diff-filter=M HEAD~1 HEAD | \
grep -v -e '^[+-]' -e '^index' | \
sed 's/diff --git a.* b\//\//g; s/.*@@\(.*\)@@.*/\1/g; s/^ -//g; s/,[0-9]*//g; s/\(^[0-9]*\) +/\1-/g;'

and the output should look like this

/some/file1
startline1-startline2
/some/file2
startline3-startline4
...
like image 171
Saurabh P Bhandari Avatar answered May 25 '26 07:05

Saurabh P Bhandari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!