简体   繁体   English

Shell脚本在有条件的情况下删除小于xMB的文件

[英]Shell script to delete files smaller than xMB with condition

I'm trying to write a script to delete the smallest file if inside the folder has more than one file smaller than 10MB, but I did not succeed. 我试图编写一个脚本来删除最小文件,如果该文件夹内有多个小于10MB的文件,但是我没有成功。

In my attempt 在我的尝试

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

Remove all less than 10 Mb, I need to remove only the smallest if inside the folder have 2 files smaller than 10MB recursively. 删除所有小于10 Mb的文件,如果文件夹中递归地包含2个小于10 MB的文件,则仅需要删除最小的文件。

Any can help-me? 有什么可以帮我吗?

An option is to loop through the output of find and then keep track of then number of files and keep track of the smallest file, so at the end you can remove it: 一种选择是遍历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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM