Git diff: is it possible to show ONLY changed lines

微笑、不失礼 提交于 2019-12-03 00:10:33

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 $_'
metacubed

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.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!