如何写文件内容对比脚本

wen 实用脚本 27

本文目录导读:

如何写文件内容对比脚本

  1. Python实现(推荐)
  2. Bash脚本实现(Linux/Unix)
  3. 使用现有工具的脚本
  4. 使用建议

Python实现(推荐)

基础行对比脚本

#!/usr/bin/env python3
"""对比脚本
支持:逐行对比、忽略空白、显示差异行号
"""
import sys
import difflib
def compare_files(file1, file2, ignore_whitespace=False):
    """对比两个文件内容"""
    try:
        with open(file1, 'r', encoding='utf-8') as f1:
            lines1 = f1.readlines()
        with open(file2, 'r', encoding='utf-8') as f2:
            lines2 = f2.readlines()
    except FileNotFoundError as e:
        print(f"错误:文件未找到 - {e.filename}")
        return False
    except Exception as e:
        print(f"错误:读取文件失败 - {e}")
        return False
    # 忽略空白选项
    if ignore_whitespace:
        lines1 = [line.strip() for line in lines1]
        lines2 = [line.strip() for line in lines2]
    # 使用difflib生成差异
    differ = difflib.Differ()
    diff = list(differ.compare(lines1, lines2))
    # 显示差异
    has_diff = False
    print(f"\n对比文件: {file1} vs {file2}\n")
    print("差异列表:")
    print("-" * 50)
    for i, line in enumerate(diff):
        if line.startswith('+ ') or line.startswith('- ') or line.startswith('? '):
            has_diff = True
            print(f"行 {i+1}: {line}")
    if not has_diff:
        print("两个文件完全相同")
    return True
def main():
    if len(sys.argv) < 3:
        print("用法: python compare_files.py <文件1> <文件2> [--ignore-whitespace]")
        sys.exit(1)
    file1 = sys.argv[1]
    file2 = sys.argv[2]
    ignore_whitespace = '--ignore-whitespace' in sys.argv
    compare_files(file1, file2, ignore_whitespace)
if __name__ == "__main__":
    main()

增强版对比脚本(带详细报告)

#!/usr/bin/env python3
"""
高级文件对比脚本
"""
import os
import hashlib
from datetime import datetime
class FileComparator:
    def __init__(self):
        self.differences = []
        self.stats = {
            'total_lines_1': 0,
            'total_lines_2': 0,
            'added_lines': 0,
            'removed_lines': 0,
            'modified_lines': 0
        }
    def get_file_info(self, filepath):
        """获取文件基本信息"""
        info = {
            'path': filepath,
            'size': os.path.getsize(filepath),
            'modified': datetime.fromtimestamp(os.path.getmtime(filepath))
        }
        # 计算MD5
        with open(filepath, 'rb') as f:
            info['md5'] = hashlib.md5(f.read()).hexdigest()
        return info
    def compare_exact(self, file1, file2):
        """精确对比"""
        info1 = self.get_file_info(file1)
        info2 = self.get_file_info(file2)
        print(f"文件1: {info1['path']} (大小: {info1['size']}字节, MD5: {info1['md5']})")
        print(f"文件2: {info2['path']} (大小: {info2['size']}字节, MD5: {info2['md5']})")
        if info1['md5'] == info2['md5']:
            return True, "文件完全相同"
        return False, "文件不同"
    def compare_lines(self, file1, file2, context_lines=3):
        """逐行对比,显示上下文"""
        with open(file1, 'r', encoding='utf-8') as f1:
            lines1 = f1.readlines()
        with open(file2, 'r', encoding='utf-8') as f2:
            lines2 = f2.readlines()
        self.stats['total_lines_1'] = len(lines1)
        self.stats['total_lines_2'] = len(lines2)
        # 对比差异
        max_lines = max(len(lines1), len(lines2))
        print(f"\n详细对比报告:")
        print("=" * 60)
        for i in range(max_lines):
            line1 = lines1[i].rstrip() if i < len(lines1) else ""
            line2 = lines2[i].rstrip() if i < len(lines2) else ""
            if line1 != line2:
                # 显示上下文
                start = max(0, i - context_lines)
                end = min(max_lines, i + context_lines + 1)
                if i > 0 and i - context_lines <= 0:
                    print(f"\n--- 第 {i+1} 行差异 ---")
                if len(lines1) > i and len(lines2) <= i:
                    print(f"- [文件1] 第 {i+1} 行: {line1}")
                    self.stats['removed_lines'] += 1
                elif len(lines1) <= i and len(lines2) > i:
                    print(f"+ [文件2] 第 {i+1} 行: {line2}")
                    self.stats['added_lines'] += 1
                else:
                    print(f"- [文件1] 第 {i+1} 行: {line1}")
                    print(f"+ [文件2] 第 {i+1} 行: {line2}")
                    self.stats['modified_lines'] += 1
        self.print_statistics()
        return len(self.differences) == 0
    def print_statistics(self):
        """打印统计信息"""
        print("\n统计信息:")
        print("-" * 60)
        print(f"文件1总行数: {self.stats['total_lines_1']}")
        print(f"文件2总行数: {self.stats['total_lines_2']}")
        print(f"新增行数: {self.stats['added_lines']}")
        print(f"删除行数: {self.stats['removed_lines']}")
        print(f"修改行数: {self.stats['modified_lines']}")
        print(f"总差异: {self.stats['added_lines'] + self.stats['removed_lines'] + self.stats['modified_lines']}")
def main():
    import sys
    if len(sys.argv) < 3:
        print("用法:")
        print("  python compare.py <文件1> <文件2>")
        print("  python compare.py <文件1> <文件2> --exact  (精确对比)")
        sys.exit(1)
    file1, file2 = sys.argv[1], sys.argv[2]
    comparator = FileComparator()
    if '--exact' in sys.argv:
        identical, message = comparator.compare_exact(file1, file2)
        print(f"结果: {message}")
    else:
        comparator.compare_lines(file1, file2)
if __name__ == "__main__":
    main()

Bash脚本实现(Linux/Unix)

#!/bin/bash
#
# 文件对比脚本
# 支持:基本对比、差异统计、格式输出
#
compare_files() {
    local file1=$1
    local file2=$2
    # 检查文件是否存在
    if [[ ! -f "$file1" ]]; then
        echo "错误: 文件不存在 - $file1"
        return 1
    fi
    if [[ ! -f "$file2" ]]; then
        echo "错误: 文件不存在 - $file2"
        return 1
    fi
    echo "对比文件: $file1 vs $file2"
    echo "----------------------------------------"
    # 使用diff命令对比
    if diff -q "$file1" "$file2" &>/dev/null; then
        echo "文件完全相同"
        return 0
    else
        echo "文件存在差异"
        # 统计差异
        local added=$(diff -u "$file1" "$file2" | grep "^+" | grep -v "^+++" | wc -l)
        local removed=$(diff -u "$file1" "$file2" | grep "^-" | grep -v "^---" | wc -l)
        echo ""
        echo "差异统计:"
        echo "  新增行: $added"
        echo "  删除行: $removed"
        # 显示差异详情
        echo ""
        echo "差异详情:"
        echo "----------------------------------------"
        diff -u "$file1" "$file2" | head -100
        return 1
    fi
}
# 主函数
main() {
    if [[ $# -lt 2 ]]; then
        echo "用法: $0 <文件1> <文件2>"
        echo "选项:"
        echo "  --brief     仅显示是否相同"
        echo "  --stat      只显示统计信息"
        echo "  --side-by-side  并排显示差异"
        exit 1
    fi
    local file1=$1
    local file2=$2
    shift 2
    # 处理选项
    for opt in "$@"; do
        case $opt in
            --brief)
                if diff -q "$file1" "$file2" &>/dev/null; then
                    echo "相同"
                else
                    echo "不同"
                fi
                exit 0
                ;;
            --stat)
                diff --stat "$file1" "$file2"
                exit 0
                ;;
            --side-by-side)
                diff -y "$file1" "$file2"
                exit 0
                ;;
        esac
    done
    compare_files "$file1" "$file2"
}
# 执行主函数
main "$@"

使用现有工具的脚本

使用diff的封装脚本

#!/bin/bash
#
# diff_wrapper.sh - diff工具的封装
#
compare_with_diff() {
    local file1=$1
    local file2=$2
    local format=${3:-"unified"}  # 默认统一格式
    case $format in
        "unified")
            echo "统一格式对比:"
            diff -u "$file1" "$file2"
            ;;
        "context")
            echo "上下文格式对比:"
            diff -c "$file1" "$file2"
            ;;
        "side")
            echo "并排格式对比:"
            diff -y "$file1" "$file2"
            ;;
        "stat")
            echo "统计信息:"
            diff --stat "$file1" "$file2"
            ;;
        *)
            echo "未知格式: $format"
            echo "可用格式: unified, context, side, stat"
            ;;
    esac
}
# 主逻辑
if [[ $# -lt 2 ]]; then
    echo "用法: $0 <文件1> <文件2> [格式]"
    echo "格式: unified|context|side|stat"
    exit 1
fi
compare_with_diff "$1" "$2" "$3"

使用建议

安装使用

# Python脚本
chmod +x compare_files.py
./compare_files.py file1.txt file2.txt
# Bash脚本
chmod +x compare.sh
./compare.sh file1.txt file2.txt
# 使用现有工具
sudo apt-get install meld     # 图形化对比工具
sudo apt-get install vimdiff  # Vim对比工具

选择建议

  1. 简单对比: 使用系统的 diff 命令
  2. 详细报告: Python增强版脚本
  3. 图形界面: Meld, Beyond Compare等工具
  4. 自动化集成: 在CI/CD中使用Python脚本

示例用法

# Python基本使用
python compare_files.py old.txt new.txt
# Python增强版
python advanced_compare.py old.txt new.txt
# Bash版本
./compare.sh old.txt new.txt --side-by-side
# 使用diff
diff -u old.txt new.txt > patch.diff

需要任何特定功能或修改吗?

抱歉,评论功能暂时关闭!