如何查找超过 1GB 的文件夹并在 linux 终端中执行另一个命令?

xmu*_*mux 5 linux unix terminal console

我想找到大小超过 1GB 的文件夹,如果它们超过了,那么我想删除它们。

我发现了一些命令,比如

find /some/path -type d -size +1G -exec ls {} \;
Run Code Online (Sandbox Code Playgroud)

或者

du -h /some/path | grep ^[0-9.]*G
Run Code Online (Sandbox Code Playgroud)

或(超过 600M)

du -h /some/path/ | grep ^[6-9][0-9][0-9][0-9.]*M | sort
Run Code Online (Sandbox Code Playgroud)

但这两个命令对我并没有真正的帮助,因为 find 命令没有找到任何文件夹,尽管有超过 1GB 的文件夹,但 linux 认为它们是一些小 KB。有什么命令可以实现吗?

Pet*_*r.O 4

处理文件/目录名称时的一个常见问题是它们包含空格。*nix 文件路径甚至可以包含\n换行符。要解决所有空白问题,您需要使用分隔符\x00

#!/bin/bash
#
# Parameter 1 ("$1"):  Remove sub-directories from this directory
# Parameter 2 ("$2"):  Remove sub-directories larger than this many bytes 
#
# Example, To remove sub-directories bigger than 1 GB from your HOME directory
#   
#    script "$HOME"  $((2**30))     
#        
dir="$1"; shopt -s extglob; dir="${dir%%+(/)}"  # remove trailing / from directory path
[[ -d "$dir" ]] || { echo "\$1: directory NOT found: $1"; exit 1; }

size=$2  # size in bytes
[[ -z $2 || -n ${2//[0-9]} ]] && { echo "\$2: size-threshold must be numeric: $2"; exit 2; }

du -0b "$dir" |                        # output with \x00 as end-of-path
 sort -zrn  |                          # sort dirs,largest first
  awk -vRS="\x00" -vORS="\x00" -v"size=$size" -v"dir=$dir" -v"prev=\x00" '{
     if( $1<=size ) next               # filter by size; skip small dirs
     match( $0, "\x09" )               # find du TAB-delimiter           
     path = substr( $0, RSTART+1 )     # get directory path 
     if( path ~ "^"dir"/*$" ) next     # filter base dir; do not kill it! 
     match( path, "^" prev ".+" )      # print (ie. process) parent dirs only
     if( RSTART == 0 ) { print path }
     prev = path }' |
   xargs -0 -I{} echo rm -vr {}        # remove the `echo` to run live!!!!
Run Code Online (Sandbox Code Playgroud)