1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

重複ファイルを探す そして 消す

Last updated at Posted at 2021-02-21

無駄な重複ファイル、消したいですよね。

学生時代大学とかで使っていた発表資料で同じものがいくつも出て来て困った…ので
重複ファイルを消す方法を考えてみました。
最善の方法ではないかもしれませんが、私はこの方法でやってみました。

アルゴリズムとしては
ファイルのCRCチェックサムを使って配列を作り、そのチェックサムと同じものがあったら削除対象にしましょう
というもの。

スクリプト例

duplicatesearch.sh}
# !/bin/bash

IFS=$'\n' #区切り文字を改行だけにした。

list1=($(find $1 -type f -print0 | xargs -0 cksum)) # -print0 と -0 は日本語とかが入っているファイル名に有効。
list2=($(find $2 -type f -print0 | xargs -0 cksum)) #  md5sum なども考えられたが、難しいのでcksumにした。

for i in ${list1[@]}
do
        I1=$(echo ${i}|cut -d" " -f1)
        I2=$(echo ${i}|cut -d" " -f3-)
        array[${I1}]=${I2}#連想配列にしたかったが、うまくいかなかった。とりあえずこれで動く。
done

for j in ${list2[@]}
do
        J1=$(echo ${j}|cut -d" " -f1)
        if [ -f ${array[${J1}]} ] && [ x != x${array[${J1}]} ]
        then
                echo rm \"${array[${J1}]}\" #スペースが入っていたりすると上手くコマンドが機能しないので、\"で対処。
        fi
done

ミソは特にないです。出力先を変えていろいろ試してみてください。
すごく時間がかかりますそれは並列化されていないから。それが悩みの種。
あと、いきなり削除とかはやめて一度出力したリストを眺めて本当に消してもいいのか確認した方が良いでしょう。

使い方

chmod 755 ./duplicatesearch.sh
./duplicatesearch.sh フォルダ(削除したいほうのフォルダ) フォルダ(マッチさせたいフォルダ)

てなかんじ。
以上。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?