Search code examples
gitdiffgit-diff

Git diff: is it possible to show ONLY changed lines


I'm trying to get only new version of lines which have changed and not all the other info which git diff shows.

For:

git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix

It shows:

diff --git file1 file2
index d9db605..a884b50 100644
--- file1
+++ file2
@@ -16 +16 @@ bla bla bla
-old text
+new text

what I want to see is only:

new text

Is it possible?


Solution

  • Only added lines does not make sense in all cases. If you replaced some block of text and you happened to include a single line which was there before, git has to match and guess. Usually the output of git diff could be used as input for patch afterwards and is therefore meaningful. Only the added lines are not precisely defined as git has to guess in some cases.

    If you nevertheless want it, you cannot trust a leading + sign alone (since we cannot distinguish between file header beginning +++ and an added line that happens to begin with ++). Maybe filtering all the green line is better:

    git diff --color=always|perl -wlne 'print $1 if /^\e\[32m\+\e\[m\e\[32m(.*)\e\[m$/'
    

    for only deleted lines filter for all the red lines:

    git diff --color=always|perl -wlne 'print $1 if /^\e\[31m-(.*)\e\[m$/'
    

    to inspect the color codes in the output you could use:

    git diff --color=always|ruby -wne 'p $_'