如何查找最新修改的文​​件并使用SHELL代码删除它们

时间:2013-10-30 15:49:08

标签: bash file shell delete-file

我需要一些shell代码的帮助。现在我有了这段代码:

find $dirname -type f -exec md5sum '{}' ';' | sort | uniq --all-repeated=separate -w 33 | cut -c 35-

此代码在给定目录中查找重复文件(具有相同内容)。我需要做的是更新它 - 找出最新的(按日期)修改过的文件(来自重复文件列表),打印该文件名,并提供在终端中删除该文件的机会。

2 个答案:

答案 0 :(得分:0)

在纯粹的bash中执行此操作有点尴尬,它会更容易编写 lot 这在perl或python中。

另外,如果您打算使用bash one-liner进行此操作,则可能是可行的, 但我真的不知道怎么做。

Anyhoo,如果你真的想要一个纯粹的bash解决方案,那就是尝试做 你描述的是什么。

请注意:

  • 我实际上并没有打电话给rm,只是回应它 - 不想破坏你的文件
  • 那里有一个“读-u 1”,我并不满意。

以下是代码:

#!/bin/bash

buffer=''

function process {
    if test -n "$buffer"
    then
        nbFiles=$(printf "%s" "$buffer" | wc -l)
        echo "================================================================================="
        echo "The following $nbFiles files are byte identical and sorted from oldest to newest:"
        ls -lt -c -r $buffer
        lastFile=$(ls -lt -c -r $buffer | tail -1)
        echo

        while true
        do
            read -u 1 -p "Do you wish to delete the last file $lastFile (y/n/q)? " answer
            case $answer in
                [Yy]* ) echo rm $lastFile; break;;
                [Nn]* ) echo skipping; break;;
                [Qq]* ) exit;;
                * ) echo "please answer yes, no or quit";;
            esac
        done
        echo
    fi
}

find . -type f -exec md5sum '{}' ';' |
sort                                 |
uniq --all-repeated=separate -w 33   |
cut -c 35-                           |
while read -r line
do
    if test -z "$line"
    then
        process
        buffer=''
    else
        buffer=$(printf "%s\n%s" "$buffer" "$line")
    fi
done
process

echo "done"

答案 1 :(得分:0)

这是中实施的“天真”解决方案(除了两个外部命令:md5sum,当然,stat仅用于用户的舒适度,它不是算法的一部分)。该东西实现了100%Bash快速排序(我很自豪):

#!/bin/bash

# Finds similar (based on md5sum) files (recursively) in given
# directory. If several files with same md5sum are found, sort
# them by modified (most recent first) and prompt user for deletion
# of the oldest

die() {
   printf >&2 '%s\n' "$@"
   exit 1
}

quicksort_files_by_mod_date() {
    if ((!$#)); then
        qs_ret=()
        return
    fi
    # the return array is qs_ret
    local first=$1
    shift
    local newers=()
    local olders=()
    qs_ret=()
    for i in "$@"; do
        if [[ $i -nt $first ]]; then
            newers+=( "$i" )
        else
            olders+=( "$i" )
        fi
    done
    quicksort_files_by_mod_date "${newers[@]}"
    newers=( "${qs_ret[@]}" )
    quicksort_files_by_mod_date "${olders[@]}"
    olders=( "${qs_ret[@]}" )
    qs_ret=( "${newers[@]}" "$first" "${olders[@]}" )
}

[[ -n $1 ]] || die "Must give an argument"
[[ -d $1 ]] || die "Argument must be a directory"

dirname=$1

shopt -s nullglob
shopt -s globstar

declare -A files
declare -A hashes

for file in "$dirname"/**; do
    [[ -f $file ]] || continue
    read md5sum _ < <(md5sum -- "$file")
    files[$file]=$md5sum
    ((hashes[$md5sum]+=1))
done

has_found=0
for hash in "${!hashes[@]}"; do
    ((hashes[$hash]>1)) || continue
    files_with_same_md5sum=()
    for file in "${!files[@]}"; do
        [[ ${files[$file]} = $hash ]] || continue
        files_with_same_md5sum+=( "$file" )
    done
    has_found=1
    echo "Found ${hashes[$hash]} files with md5sum=$hash, sorted by modified (most recent first):"
    # sort them by modified date (using quicksort :p)
    quicksort_files_by_mod_date "${files_with_same_md5sum[@]}"
    for file in "${qs_ret[@]}"; do
      printf "   %s %s\n" "$(stat --printf '%y' -- "$file")" "$file"
    done
    read -p "Do you want to remove the oldest? [yn] " answer
    if [[ ${answer,,} = y ]]; then
       echo rm -fv -- "${qs_ret[@]:1}"
    fi
done

if((!has_found)); then
    echo "Didn't find any similar files in directory \`$dirname'. Yay."
fi

我猜这个剧本是不言自明的(你可以像故事一样阅读)。它使用我所知道的最佳实践,并且对于文件名中的任何愚蠢字符(例如,空格,换行符,以连字符开头的文件名,以换行符结尾的文件名等)100%安全。

它使用bash的globs,所以如果你有一个膨胀的目录树,它可能会有点慢。

有一些错误检查,但很多都丢失了,所以不要在生产中使用原样! (添加这些是一件微不足道但相当乏味的事情。)

算法如下:扫描给定目录树中的每个文件;对于每个文件,将计算其md5sum并存储在关联数组中:

  • files,其中包含文件名和值md5sums。
  • hashes,其中包含哈希值和值,其中md5sum是关键字的文件数。

完成此操作后,我们将扫描所有找到的md5sum,仅选择与多个文件对应的文件,然后选择具有此md5sum的所有文件,然后按修改日期快速排序,并提示用户。

没有找到重复时的甜蜜效果:脚本很好地告知用户它。

我不会说这是最有效的做事方式(可能更好,例如,Perl),但它真的很有趣,非常容易阅读和遵循,你可以通过学习学到很多东西它!

它使用了一些只有bash版本≥4的基本原理和功能

希望这有帮助!

备注。如果您的系统date上有-r开关,则可以将stat命令替换为:

date -r "$file"

备注。我将echo留在rm前面。如果您对脚本的行为方式感到满意,请将其删除。然后,您将拥有一个使用3个外部命令:)的脚本。