フォルダから同じファイルを削除する

フォルダから同じファイルを削除する

私はオペレーティングシステム用のパッケージを構築するためにchrootを使用しています。アーカイブにchrootがあり、ビルドプロセスが開始されたときに2回ダウンロードして抽出します。2番目のchrootフォルダのファイルと同じ(ハッシュとして)ビルドパッケージのchrootフォルダからファイルを削除するコマンドが必要です。Unix StackExchangeで複数のコマンドを試しましたが、そのうち何も機能しませんでした。

編集:完全自動でなければなりません。

ベストアンサー1

そしてfdupes

fdupes -drN dir1 dir2

これにより、両方のディレクトリで複数回見つかったすべてのエントリが削除されます。詐欺が最初に見つかった場合は、コピーが保存されます。

長いオプションがあります:

fdupes --delete --recurse --noprompt dir1 dir2

これにより、dir1同じディレクトリにある他のファイルと重複したファイルも削除されます。

GNU ツールを搭載したシステムでdir1スクリプトを直接作成すると、重複するエントリを削除してこの問題を解決できます。

#!/bin/sh

dir1=somedir
dir2=someotherdir

sums1=$(mktemp)
sums2=$(mktemp)

# Remove temporary files when done.
trap 'rm -f "$sums1" "$sums2"' EXIT

# Calculate checksums for first directory, extract only the checksums
# themselves and sort them (removing duplicate checksums).
find "$dir1" -type f -exec md5sum -z {} + |
cut -z -c -32 |
sort -z -u -o "$sums1"

# Calculate the checksums for the second directory, and sort them.
find "$dir2" -type f -exec md5sum -z {} + |
sort -z -o "$sums2"

# Join the files on the first column, extract the pathnames for the
# files in the second directory that have the same checksum as files in
# the first directory, and delete these files.
join -z "$sums1" "$sums2" |
cut -z -c 34- |
xargs -0 rm -f


# Optionally, delete empty directories in the second directory
# find "$dir2" -type d -empty -delete

上記のコードはまた、パス名をnullで終わるリストに渡して、有効なファイル名が正しく処理されるようにします。


bash上記のスクリプトの短いバリエーション:

#!/bin/bash

dir1=somedir
dir2=someotherdir

join -z \
    <(find "$dir1" -type f -exec md5sum -z {} + | cut -z -c -32 | sort -z -u)  \
    <(find "$dir2" -type f -exec md5sum -z {} + | sort -z) |
cut -z -c 34- |
xargs -0 rm -f

おすすめ記事