MOYOMOYO
이명진 · PERSONAL BLOG

MOYO

생각과 경험을 기록하는 공간입니다.

← 글 목록

중복 파일 제거 쉘 스크립트

이명진조회 2댓글 0

중복된 파일을 삭제하는 스크립트를 작성해봤다.

우분투에서 쉘 스크립트를 만들어서 실행하면 특정 디렉토리 하위의 파일들을 검색해서 중복된 파일이라고 판단하면 삭제한다.

파일 이름이 중복이면 삭제

#!/bin/bash

# 디렉토리 설정
DIR="file/path"

# 파일 이름이 같은 파일을 찾고, 용량이 더 작은 파일을 삭제
find "$DIR" -type f | while read -r file; do
    # 파일 이름만 추출 (디렉토리 경로 제외)
    filename=$(basename "$file")
    
    # 같은 이름을 가진 파일들을 찾음
    find "$DIR" -type f -name "$filename" | while read -r samefile; do
        # 원본 파일과 동일한 파일은 비교하지 않음
        if [ "$file" != "$samefile" ]; then
            size1=$(stat -c%s "$file")
            size2=$(stat -c%s "$samefile")

            if [ $size1 -gt $size2 ]; then
                echo "Deleting smaller file: $samefile"
                rm -v "$samefile"
            elif [ $size1 -lt $size2 ]; then
                echo "Deleting smaller file: $file"
                rm -v "$file"
                # 원본 파일이 삭제되었으므로 현재 파일로 동일 파일 설정
                file="$samefile"
            fi
        fi
    done
done

파일 해쉬(HASH)가 같으면 삭제

#!/bin/bash

# 디렉토리 설정
DIR="/file/path"

# 해시 값을 저장할 임시 파일 생성
tempfile=$(mktemp)

# 모든 파일의 md5 해시 값을 계산하고 임시 파일에 저장
find "$DIR" -type f -exec md5sum {} + > "$tempfile"

# 중복된 파일의 해시 값을 찾고, 첫 번째 파일을 제외한 나머지 파일을 삭제
awk '{print $1}' "$tempfile" | sort | uniq -d | while read hash; do
    grep "^$hash" "$tempfile" | tail -n +2 | awk '{print $2}' | xargs -I{} rm ->
done

# 임시 파일 삭제
rm "$tempfile"

스크립트 실행

위의 스크립트를 duplicated_file_delete.sh 로 저장 후 실행한다.

sudo bash duplicated_file_delete.sh

#중복파일 #중복삭제 #중복파일삭제 #ssh

댓글 0

등록된 댓글이 없습니다.