Skip to content
shellhacks.dev
Command Line

Show Word-Level Differences in Git with --word-diff

Show changes inside a line with git diff --word-diff, which marks removed words as [-old-] and added words as {+new+}. A regex option gives character level diffs.

2 min read
Summarize in AI

A long line changed in two places and the usual diff makes you hunt for what moved.

Shell
git init -q repo && cd repo
git config user.name Ann && git config user.email [email protected]
echo 'The quick brown fox jumps over the lazy dog' > a.txt
git add a.txt && git commit -qm one
echo 'The quick red fox jumps over the sleepy dog' > a.txt
git diff --word-diff
git diff --word-diff=porcelain | tail -n +5
git diff --word-diff-regex=. | tail -n 1
Text
diff --git a/a.txt b/a.txt
index 84102df..750ac7a 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
The quick [-brown-]{+red+} fox jumps over the [-lazy-]{+sleepy+} dog
@@ -1 +1 @@
 The quick
-brown
+red
  fox jumps over the
-lazy
+sleepy
  dog
~
The quick [-b-]r[-own-]{+ed+} fox jumps over the {+s+}l[-az-]{+eep+}y dog

The default output of --word-diff prints the line once with [-brown-]{+red+} markers where words differ, which is easier to read than two near-identical lines. --word-diff=porcelain prints one word per line with a plus or minus prefix for tools, and --word-diff-regex=. treats every character as a word, so brown to red appears as small edits. See git diff.

Without a regex a word is a run of non-space characters, so x,y is one word, and the output is plain text, not a patch you can apply. The markers can be confused with the text itself when the file contains brackets. Use --color-words on a terminal to get colors in place of the markers.

Taggedgittext
Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.