コンテンツへスキップ
uencoder

テキストの差分を比較する方法

2 つのテキスト文字列やファイルの差異を見つけ、追加、削除、変更を表示します。

问题

テキストドキュメントの 2 つのバージョン間で、何が変わったかを確認する必要があります。

前提条件

  • 差分アルゴリズムの理解
  • unified diff 形式への習熟

ステップ

  1. 1. Prepare the two texts

    Have the original (old) and modified (new) text ready. The diff algorithm compares them line by line. Ensure both texts use the same line endings (LF or CRLF) for accurate comparison.

    入力
    old: v1 | new: v2
    输出
    ready to diff
  2. 2. Compute the diff

    The diff algorithm (typically Myers diff) finds the shortest sequence of insertions and deletions to transform the old text into the new. The output shows added lines (+), removed lines (-), and context lines ( ).

    入力
    old: 'Hello world' | new: 'Hello Earth'
    输出
    -Hello world\n+Hello Earth
  3. 3. Interpret the output

    Read the diff to understand what changed. Unified diff format shows context around changes. Side-by-side diff shows both versions aligned. Use the format that best helps you understand the changes. For code, unified diff is standard.

    入力
    unified diff
    输出
    changes clearly visible

期待される結果

2 つのテキストの違いを明確に表したもの。

よくあるエラー

Entire file shows as changed
Line endings differ (LF vs CRLF). Normalize line endings before diffing.
Diff is too noisy with irrelevant changes
Increase the context size or use a word-level diff instead of line-level for finer granularity.

トラブルシューティング指引

  • If the diff seems wrong, check for invisible character differences (tabs vs spaces, BOM).
  • For large files, use a diff tool that supports streaming or chunking.

セキュリティ上の制限

  • Diffing is a read-only comparison with no security implications.

関連ツール

参考链接