5

When I have a change in a file that consists only of a single very long line, can git diff output only the part of the line that changed?

I know that git diff --word-diff will highlight in color only the parts that have changed, but it will still output the full line.

Is there an option to only output the part of the line that has changed? Or perhaps a grep pattern that could match only the colored parts of git diff --word-diff ?

1 Answer 1

7

Yes, use git diff --word-diff=porcelain.

Use a special line-based format intended for script consumption. Added/removed/unchanged runs are printed in the usual unified diff format, starting with a +/- character at the beginning of the line and extending to the end of the line. Newlines in the input are represented by a tilde ~ on a line of its own.

A small change to a long line will look something like...

~
The mouse that the cat that the dog that the 
-man
+person
  frightened and chased ran away
~

Otherwise you can search for [- and {+.

2
  • 3
    Ah so I can filter that output using grep like this: git diff --word-diff=porcelain filename | grep '^[~+-]'
    – Liam
    Commented Nov 9, 2020 at 19:49
  • But the '^[~+-]' grep pattern will also catch the initial lines (metadata) of the diff output, like --- a/README.md and +++ b/README.md so an alternative could be grep "^[~\+\-][^\+\-]" Commented Apr 12 at 7:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.