Unix-like Systems (Linux/macOS) – diff Command
Basic diff Usage
diff file1.txt file2.txt # Basic comparison
diff -u file1.txt file2.txt # Unified format
diff -y file1.txt file2.txt # Side-by-side comparison
diff -r dir1/ dir2/ # Recursive directory comparison
diff -w file1.txt file2.txt # Ignore whitespace
diff -B file1.txt file2.txt # Ignore blank lines
Advanced diff Options
diff -c file1.txt file2.txt # Context format
diff --color file1.txt file2.txt # Colored output
diff -I '^#' file1.txt file2.txt # Ignore lines matching pattern
diff -q dir1/ dir2/ # Brief directory comparison
Historical Context
The diff command originated in Unix systems and was created by Douglas McIlroy in 1974. It uses the longest common subsequence algorithm to identify differences between files.
Command-Line Tools
- git diff
git diff --no-index file1.txt file2.txt # Compare files outside repository
git diff branch1..branch2 # Compare branches
git diff --word-diff # Word-level comparison
- vimdiff
vimdiff file1.txt file2.txt # Open files in Vim with differences highlighted
- kdiff3
kdiff3 file1.txt file2.txt file3.txt # Three-way merge
Best Practices
- Text File Comparison
- Use
-wto ignore whitespace when content matters more than formatting - Use
-Bto ignore blank lines in structural comparisons - Use
-ufor unified format in patch creation
- Binary File Comparison
- Use specialized tools (FC /b on Windows)
- Consider checksum comparison (md5sum, sha256sum)
- Use hex editors for detailed analysis
- Directory Comparison
- Use
-rfor recursive comparison - Consider exclusion patterns for temp files
- Use
-qfor quick overview of differences
Integration with Version Control
# Git-based comparison
git diff HEAD~1 HEAD file.txt # Compare with previous version
git diff --stat # Overview of changes
Windows Systems
Built-in Tools
- FC (File Compare):
fc file1.txt file2.txt # Basic text comparison
fc /b file1.exe file2.exe # Binary comparison
fc /l file1.txt file2.txt # ASCII comparison
fc /n file1.txt file2.txt # Display line numbers
- COMP:
comp file1.txt file2.txt # Basic comparison
comp /m file1.txt file2.txt # Show mismatches
comp /n=50 file1.txt file2.txt # Compare first 50 bytes
PowerShell Commands
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt)
Cross-Platform Alternatives
GUI Tools
- WinMerge
- Features: Visual diff and merge
- Platforms: Windows (native), others via Wine
- License: Open-source
2. Meld
- Features: Three-way comparison, directory scanning
- Platforms: Linux (native), Windows, macOS
- License: Open-source
3. Beyond Compare
- Features: Directory sync, text merge, binary comparison
- Platforms: Windows, macOS, Linux
- License: Commercial