1

How can one show the words added to a file between two commits (say HEAD vs HEAD^)?

git diff seems to show "additions", which I believe are defined as lines added. But this is not as useful when you are marking up written text in a git repository.

1615903
  • 32,635
  • 12
  • 70
  • 99
George
  • 6,927
  • 4
  • 34
  • 67

2 Answers2

2

Try

git diff --color-words HEAD HEAD^

From the docs:

--word-diff-regex=<regex>

Use to decide what a word is, instead of considering runs of non-whitespace to be a word. Also implies --word-diff unless it was already enabled.

Every non-overlapping match of the is considered a word. Anything between these matches is considered whitespace and ignored(!) for the purposes of finding differences. You may want to append |[^[:space:]] to your regular expression to make sure that it matches all non-whitespace characters. A match that contains a newline is silently truncated(!) at the newline.

For example, --word-diff-regex=. will treat each character as a word and, correspondingly, show differences character by character.

The regex can also be set via a diff driver or configuration option, see gitattributes[5] or git-config[1]. Giving it explicitly overrides any diff driver or configuration setting. Diff drivers override configuration settings.

--color-words[=<regex>] Equivalent to --word-diff=color plus (if a regex was specified) --word-diff-regex=<regex>.

Check out a longer description of other suggestions for more powerful diffs here

Community
  • 1
  • 1
saladi
  • 3,103
  • 6
  • 36
  • 61
  • This is great -- but is there a way to show the total number of words added/deleted rather than just exposing the changes visually? – George Sep 30 '17 at 21:10
  • I'm sure that could be hacked together. Sounds like it'd be worth opening a new question for that... – saladi Sep 30 '17 at 21:28
  • Actually, take a look at this question and answer that does exactly that: https://stackoverflow.com/questions/2874318 – saladi Sep 30 '17 at 21:31
0

If I interpret your question, correctly, you are looking for a way to diff two commits which would show differences on a word level, rather than just a line level.

To do that you could use an appropriate external diff tool, e.g. kdiff3, that can handle showing differences of parts of a line. kdiff3 will highlight every character difference.

There are other answers on StackOverflow that detail how to set up a diff tool in git. For example Git: How configure KDiff3 as merge tool and diff tool

Klas Mellbourn
  • 42,571
  • 24
  • 140
  • 158