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?
Only added lines does not make sense in all cases. If you replaced some block of text and you happend 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. 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 $_'
If you specifically want only the new text
part, then use the following:
git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix | egrep "^\+"
This is basically your code, piped into the egrep
command with a regex. The regex will filter only lines starting with a plus sign.
You can use:
git diff -U0 <commit-hash> | grep "^\+\""
This will give your output as "+new text"
Here is an answer using grep
. It retains the original red/green colors for readability. I provided a few variations in syntax:
git diff --color | grep --color=never $'^\e\[3[12]m'
git diff --color | grep --color=never $'^\033\[3[12]m'
git diff --color | grep --color=never -P '^\e\[3[12]m'
git diff --color | grep --color=never -P '^\033\[3[12]m'
Explanation:
git diff --color
is needed to prevent git from disabling the color when it is piping.
grep --color=never
prevents grep from highlighting the matched string (which removes the original color from the original command)
- Match lines that start with red (
\e[31m
) or green (\e[32m
) escape codes.
- The
$'...'
(ANSI-C quoting syntax) or -P
(perl syntax) is to let grep
to interpret \e
or \033
as an ESC
character.