linux

Linux中如何删除重复文件

小樊
50
2025-07-06 06:21:13
栏目: 智能运维

在Linux中删除重复文件可以通过多种方法实现,以下是几种常用的方法:

方法一:使用fdupes工具

  1. 安装fdupes

    sudo apt-get install fdupes  # Debian/Ubuntu
    sudo yum install fdupes      # CentOS/RHEL
    sudo dnf install fdupes      # Fedora
    
  2. 查找并删除重复文件

    • 查找当前目录及其子目录中的重复文件:
      fdupes -r /path/to/search
      
    • 删除重复文件(保留一个副本):
      fdupes -rdN /path/to/search
      
      其中,-r表示递归搜索,-d表示显示重复文件的路径,-N表示删除重复文件。

方法二:使用findmd5sum脚本

  1. 创建一个脚本来查找和删除重复文件

    #!/bin/bash
    
    if [ $# -eq 0 ]; then
        echo "Usage: $0 <directory>"
        exit 1
    fi
    
    DIRECTORY=$1
    TEMP_FILE=$(mktemp)
    
    find "$DIRECTORY" -type f -print0 | sort -z | md5sum | awk '/^..../ {print $2}' | cut -d'/' -f1-3 > "$TEMP_FILE"
    
    while read -r line; do
        if [ $(grep -c "^$line$" "$TEMP_FILE") -gt 1 ]; then
            echo "Duplicate files found for: $line"
            find "$DIRECTORY" -type f -name "$line" | tee /tmp/duplicates.txt
            read -p "Do you want to delete these files? (y/n): " response
            if [ "$response" == "y" ]; then
                find "$DIRECTORY" -type f -name "$line" -delete
                echo "Deleted duplicate files."
            else
                echo "No files were deleted."
            fi
        fi
    done < "$TEMP_FILE"
    
    rm "$TEMP_FILE"
    
  2. 运行脚本

    chmod +x delete_duplicates.sh
    ./delete_duplicates.sh /path/to/search
    

方法三:使用dedupe-cli工具

  1. 安装dedupe-cli

    pip install dedupe-cli
    
  2. 运行dedupe-cli进行去重

    dedupe-cli -i /path/to/search -o /path/to/output -m 0.9
    

    其中,-i指定输入目录,-o指定输出目录,-m指定相似度阈值(0到1之间)。

注意事项

通过以上方法,你可以有效地在Linux系统中查找并删除重复文件。

0
看了该问题的人还看了