脚本怎样清理冗余代码行

wen 实用脚本 28

本文目录导读:

脚本怎样清理冗余代码行

  1. Shell/Bash 脚本清理
  2. Python 脚本清理
  3. 针对特定语言的清理
  4. 完整的清理脚本
  5. 使用现成工具
  6. 使用建议

我来介绍几种清理冗余代码行的方法,针对不同场景:

Shell/Bash 脚本清理

删除空行和纯注释行

# 删除所有空行
sed -i '/^$/d' file.py
# 删除只有空白字符的行
sed -i '/^[[:space:]]*$/d' file.py
# 删除纯注释行(以#开头)
sed -i '/^[[:space:]]*#/d' file.py

组合清理

#!/bin/bash
# 清理空行、注释行和尾部空白
clean_script() {
    local file="$1"
    sed -i '/^[[:space:]]*$/d' "$file"        # 删除空行
    sed -i '/^[[:space:]]*\/\//d' "$file"     # 删除//注释(C/Java等)
    sed -i '/^[[:space:]]*#/d' "$file"        # 删除#注释(Python/Shell等)
    sed -i 's/[[:space:]]*$//' "$file"        # 删除行尾空格
}

Python 脚本清理

基础清理函数

def clean_code_lines(file_path):
    """清理代码中的冗余行"""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    cleaned = []
    for line in lines:
        # 跳过空行(忽略空白字符)
        if line.strip() == '':
            continue
        # 跳过纯注释行
        if line.strip().startswith('#') or line.strip().startswith('//'):
            continue
        # 去除行尾空白
        cleaned.append(line.rstrip() + '\n')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(cleaned)

高级清理(检测重复行)

from collections import Counter
def remove_duplicate_lines(file_path):
    """删除完全重复的代码行"""
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    # 统计每行出现次数
    line_counter = Counter(lines)
    # 只保留出现一次的行
    unique_lines = [line for line in lines if line_counter[line] == 1]
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(unique_lines)

针对特定语言的清理

JavaScript/TypeScript

// Node.js 脚本清理
const fs = require('fs');
function cleanJS(filePath) {
    let content = fs.readFileSync(filePath, 'utf8');
    // 删除空行
    content = content.replace(/^\s*[\r\n]/gm, '');
    // 删除单行注释(保留多行注释和字符串内的)
    content = content.replace(/\/\/[^\n]*/g, '');
    // 删除多余空白
    content = content.replace(/[ \t]+$/gm, '');
    fs.writeFileSync(filePath, content);
}

Python 使用 AutoPEP8

import autopep8
def clean_python_file(file_path):
    """使用 autopep8 清理 Python 文件"""
    with open(file_path, 'r', encoding='utf-8') as f:
        code = f.read()
    # 清理多余空白和空行
    cleaned = autopep8.fix_code(code, options={
        'aggressive': 2,
        'max_line_length': 100
    })
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(cleaned)

完整的清理脚本

#!/usr/bin/env python3
"""
代码冗余行清理工具
支持: Python, JavaScript, Java, C/C++, Shell
"""
import re
import sys
def detect_language(filename):
    """根据扩展名检测语言"""
    ext = filename.split('.')[-1].lower()
    lang_configs = {
        'py': {'comments': ['#'], 'multiline': (''' , """)},
        'js': {'comments': ['//'], 'multiline': ('/*', '*/')},
        'java': {'comments': ['//'], 'multiline': ('/*', '*/')},
        'c': {'comments': ['//'], 'multiline': ('/*', '*/')},
        'cpp': {'comments': ['//'], 'multiline': ('/*', '*/')},
        'sh': {'comments': ['#'], 'multiline': None},
        'yaml': {'comments': ['#'], 'multiline': None},
    }
    return lang_configs.get(ext, {'comments': ['#', '//'], 'multiline': None})
def clean_duplicate_code(file_path):
    """清理冗余代码行"""
    lang_config = detect_language(file_path)
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    cleaned = []
    seen_lines = set()
    in_multiline = False
    for line in lines:
        stripped = line.strip()
        # 跳过空行
        if not stripped:
            continue
        # 忽略多行注释
        if lang_config['multiline']:
            start, end = lang_config['multiline']
            if in_multiline:
                if end in stripped:
                    in_multiline = False
                continue
            if start in stripped:
                in_multiline = True
                continue
        # 跳过单行注释
        is_comment = False
        for comment_marker in lang_config['comments']:
            if stripped.startswith(comment_marker):
                is_comment = True
                break
        if is_comment:
            continue
        # 删除重复行(完全相同的行)
        if line not in seen_lines:
            seen_lines.add(line)
            cleaned.append(line.rstrip() + '\n')
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(cleaned)
    print(f"清理完成: 从 {len(lines)} 行减少到 {len(cleaned)} 行")
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python clean_code.py <文件路径>")
        sys.exit(1)
    clean_duplicate_code(sys.argv[1])

使用现成工具

对于 Python 项目

# 使用 black 格式化
black your_file.py
# 使用 ruff 检查和修复
ruff check --fix your_file.py
# 使用 autoflake 删除未使用的导入
autoflake --remove-all-unused-imports --in-place your_file.py

对于 JavaScript 项目

# 使用 prettier
npx prettier --write your_file.js
# 使用 ESLint 修复
npx eslint --fix your_file.js

使用建议

  1. 备份原文件:清理前先创建备份
  2. 逐步清理:不要一次性清理太多,避免破坏代码逻辑
  3. 版本控制:使用 Git 等版本控制,方便回退
  4. 测试:清理后运行测试确保功能正常
  5. 自定义规则:根据项目需求调整清理规则

选择最适合你项目需求的脚本即可。

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