LoginSignup
0
0

More than 3 years have passed since last update.

ディレクトリ階層内に存在する重複ファイルを検索(シェルスクリプト)

Last updated at Posted at 2021-04-24

こんにちは。
ディレクトリ階層内の重複ファイルを検索しました(シェルスクリプト)。ファイル名ではなく md5 値が等しい重複ファイルを探します1uniq -f1 -D を使っていますが、その際にファイル名が blank space を含む場合へ対処しています(uniq_duplicate_f2

出力は、fdupes, jdupes コマンドに似せて、重複グループ間を空行で区切っています。GNU find, GNU uniq を用いています。

ただし実用性(?)よりも、「シェルスクリプト+パイプライン」で実現させる試みの意図が少々強いので悪しからず。

$ ./fdupes.sh
./memo.txt
./memo/memo.txt
fdupes.sh
#!/bin/sh

dir="."
size="0c"
TAB=$(printf '\t')

# functions
size_csum_f() {
  file="$1"
  siz=$(wc -c "$file" | awk '{print $1}')
  csum=$(md5sum "$file" | awk '{print $1}')
  printf "%s\t%s\t%s\n" "$file" "$siz" "$csum"
}

uniq_duplicate_f() {
  tr ' ' '\0' |
  sort -t"$TAB" -k2nr |
  guniq -f1 -D |
  tr '\0' ' '
}

# main
gfind $dir -size +"$size" -type f -printf "%p\t%s\n" |
  uniq_duplicate_f | cut -f1 |
  while read -r file; do size_csum_f "$file"; done |
  uniq_duplicate_f | 
  while read -r line;
    do
      size_csum=$(echo "$line" | cut -f 2-3);
      [ "$size_csum" != "$prev" ] && echo;
      prev="$size_csum";
      echo "$line" | cut -f1;
    done 

  1. 参考:「指定ディレクトリ階層内に存在する重複ファイルを検索(ファイル名およびサイズが等しい条件)」 

  2. guniq -f1 -D を使っており、-f1 でスキップを使っています。ファイル名の blank space がその対象にならないように、直前に tr ' ' '\0' を行なって回避しています。 

0
0
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
0
0