用于删除小于xMB的条件的Shell脚本

时间:2017-07-19 23:12:11

标签: linux bash shell scripting rm

我试图编写一个脚本来删除最小的文件,如果文件夹中有多个小于10MB的文件,但我没有成功。

在我的尝试中

find . -type f -size -10M -exec rm {} +

删除所有小于10 Mb,我只需要删除文件夹中只有最小的文件,递归时有2个小于10MB的文件。

任何可以帮助我?

1 个答案:

答案 0 :(得分:0)

一个选项是遍历find的输出,然后跟踪当时的文件数量并跟踪最小的文件,所以最后你可以删除它:

#!/bin/bash

path=/path/to/dir # replace here with your path

while read -d '' -r dir;do

    files_count=0
    unset min
    unset smallest_file

    while read -d '' -r file;do

            let files_count++
            min_size="$(du -b "${file}"|cut -f1)"
            min=${min:-"$min_size"}
            smallest_file=${smallest_file:-"$file"}

            if (( min_size < min ));then
                    min=$min_size
                    smallest_file=$file
            fi

    done < <(find "${dir}" -type f -size -10M -maxdepth 1 -print0)

    if (( files_count >= 2 ));then

            echo "$smallest_file"
            #rm -v "$smallest_file"

    fi

done < <(find "${path}" -type d -print0)