6
3

More than 3 years have passed since last update.

単語単位の差分を出したいときには git-diff を使える

Last updated at Posted at 2021-02-18

次の2つのファイルがあったとします。

1.txt
hogehoge 1 fugafuga

2.txt
hogehoge l fugafuga

diff を使って違いを見つけようとしますが、行単位での比較になるのであまり参考になりません。
(今回利用したdiff は diff (GNU diffutils) 2.8.1 です)

$ diff -u {1,2}.txt
--- 1.txt       2021-02-18 11:09:33.000000000 +0900
+++ 2.txt       2021-02-18 11:09:30.000000000 +0900
@@ -1 +1 @@
-hogehoge 1 fugafuga
+hogehoge l fugafuga

git-diff を Git 管理外で使う。行単位の差分

git-diff は --no-index オプションをつけると、Git管理下でなくても動作します。ここでは行単位の差分を表示しています。

公式ドキュメント: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt-emgitdiffemltoptionsgt--no-index--ltpathgtltpathgt

$ git diff --no-index {1,2}.txt
diff --git a/1.txt b/2.txt
index 207832ae..abab571a 100644
--- a/1.txt
+++ b/2.txt
@@ -1 +1 @@
-hogehoge 1 fugafuga
+hogehoge l fugafuga

git-diff を使って、単語単位の差分を見る

git-diff には単語単位での差分を表示する --word-diff オプションがあります。

公式ドキュメント: https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---word-diffltmodegt

$ git diff --word-diff --no-index {1,2}.txt 
diff --git a/1.txt b/2.txt
index 96b1a710..38ca2702 100644
--- a/1.txt
+++ b/2.txt
@@ -1 +1 @@
hogehoge [-1-]{+l+} fugafuga

私の使っているシェルでは色を有効化しているので、次のような見た目になります。

image.png

word-diff のモード

--word-diff にはいくつかのモードがあります。

plain

git diff --word-diff=plain --no-index {1,2}.txt

image.png

color

git diff --word-diff=color --no-index {1,2}.txt

image.png

porcelain

git diff --word-diff=porcelain --no-index {1,2}.txt

image.png

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3