簡體   English   中英

如何只刪除某個目錄下的復制文件(具有相同的cksum)

[英]how to remove only the duplication file under some directory ( with the same cksum )

我構建以下腳本,以刪除具有相同cksum(或content)的文件

問題在於,該腳本可以兩次刪除文件,如以下示例所示(輸出)

我的目標是僅刪除復制文件,而不是源文件,

腳本輸出:

  Starting:
  Same: /tmp/File_inventury.out /tmp/File_inventury.out.1
  Remove: /tmp/File_inventury.out.1
  Same: /tmp/File_inventury.out.1 /tmp/File_inventury.out
  Remove: /tmp/File_inventury.out
  Same: /tmp/File_inventury.out.2 /tmp/File_inventury.out.3
  Remove: /tmp/File_inventury.out.3
  Same: /tmp/File_inventury.out.3 /tmp/File_inventury.out.2
  Remove: /tmp/File_inventury.out.2
  Same: /tmp/File_inventury.out.4 /tmp/File_inventury.out
  Remove: /tmp/File_inventury.out
  Done.

我的腳本:

 #!/bin/bash
  DIR="/tmp"
 echo "Starting:"
  for file1 in ${DIR}/File_inventury.out*; do
    for file2 in ${DIR}/File_inventury.out*; do
            if [ $file1 != $file2 ]; then
                    diff "$file1" "$file2" 1>/dev/null
                    STAT=$?
                    if [ $STAT -eq 0 ]
                     then
                            echo "Same: $file1 $file2"
                            echo "Remove: $file2"
                            rm "$file1"
                            break
                    fi
            fi
    done
 done
 echo "Done."

無論如何,我想聽聽–關於如何刪除具有相同內容或cksum的文件的其他選擇(實際上只需要刪除重復文件,而不是主文件)

請建議我們如何在solaris操作系統下做到這一點(例如,選擇-查找一個liner,awk,sed等)。

這個版本應該更有效。 我對paste匹配正確的行感到不安,但是看起來POSIX指定默認對glob'ing進行排序。

for i in *; do
    date -u +%Y-%m-%dT%TZ -r "$i";
done > .stat;         #store the last modification time in a sortable format
cksum * > .cksum;     #store the cksum, size, and filename
paste .stat .cksum |  #data for each file, 1 per row
    sort |            #sort by mtime so original comes first
    awk '{
        if($2 in f)
            system("rm -v " $4); #rm if we have seen an occurrence of this cksum
        else
            f[$2]++              #count the first occurrence
    }'

這應該以O(n * log(n))時間運行,每個文件僅讀取一次。

您可以將其放在shell腳本中,如下所示:

#!/bin/sh

for i in *; do
    date -u +%Y-%m-%dT%TZ -r "$i";
done > .stat;
cksum * > .cksum;
paste .stat .cksum | sort | awk '{if($2 in f) system("rm -v " $4); else f[$2]++}';
rm .stat .cksum;
exit 0;

或單線執行:

for i in *; do date -u +%Y-%m-%dT%TZ -r "$i"; done > .stat; cksum * > .cksum; paste .stat .cksum | sort | awk '{if($2 in f) system("rm -v " $4); else f[$2]++}'; rm .stat .cksum;

我使用數組作為索引映射。 所以我認為這只是O(n)嗎?

#!/bin/bash

arr=()
dels=()
for f in $1; do
  read ck x fn <<< $(cksum $f)
  if [[ -z ${arr[$ck]} ]]; then 
    arr[$ck]=$fn
  else
    echo "Same: ${arr[$ck]} $fn"
    echo "Remove: $fn"
    rm $fn
  fi
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM