DEV Community

arenasbob2024-cell
arenasbob2024-cell

Posted on • Originally published at viadreams.cc

Text Diff Checker: Compare Files Like a Pro Developer

If you've ever compared two versions of a config file or code snippet, you've used a diff checker. Here's how they work and which tools to use.

How Diff Algorithms Work

Most diff tools use the Longest Common Subsequence (LCS) algorithm or Myers' diff algorithm. They find the minimal set of changes needed to transform text A into text B.

Output types:

  • Unified diff: Shows changes with context (git default)
  • Side-by-side: Two columns, easy visual comparison
  • Inline: Changes highlighted within the text

Command Line Tools

git diff

git diff file.txt                  # Working vs staged
git diff --staged                  # Staged vs HEAD
git diff HEAD~3..HEAD -- file.txt  # Last 3 commits
Enter fullscreen mode Exit fullscreen mode

diff (POSIX)

diff -u file1.txt file2.txt       # Unified format
diff -y file1.txt file2.txt       # Side-by-side
Enter fullscreen mode Exit fullscreen mode

colordiff

colordiff -u old.txt new.txt      # Colored unified diff
Enter fullscreen mode Exit fullscreen mode

In Code

JavaScript

import { diffLines } from 'diff';
const changes = diffLines(oldText, newText);
changes.forEach(part => {
  const prefix = part.added ? '+' : part.removed ? '-' : ' ';
  console.log(prefix + part.value);
});
Enter fullscreen mode Exit fullscreen mode

Python

import difflib
diff = difflib.unified_diff(
    old_lines, new_lines,
    fromfile='old.txt', tofile='new.txt'
)
print('\n'.join(diff))
Enter fullscreen mode Exit fullscreen mode

Try It Online

Compare text with DevToolBox's Diff Checker - side-by-side and inline views, syntax highlighting, download diff.


What's your favorite diff tool? Share below!

Top comments (0)