我写了一个简单的shell脚本来查找大文件,主要是为了节省一些打字.这项工作正在完成:
find $dir -type f -size +"$size"M -printf '%s %p\n' | sort -rn
Run Code Online (Sandbox Code Playgroud)
我想将字节输出转换为人类可读的格式.我在网上找到了如何手动执行此操作的方法,例如,
find $dir -type f -size +"$size"M -printf '%s %p\n' | sort -rn |
awk '{ hum[1024**4]="TB"; hum[1024**3]="GB"; hum[1024**2]="MB"; hum[1024]="KB"; hum[0]="B";
for (x=1024**4; x>=1024; x/=1024){
if ($1>=x) { printf "%7.2f %s\t%s\n",$1/x,hum[x],$2;break }
}}'
Run Code Online (Sandbox Code Playgroud)
但这看起来很混乱.我想知道:是否有一种将字节转换为人类可读形式的标准方法?
当然,在目录和min-size作为输入的情况下,任何产生以下输出的替代方法也是受欢迎的:
1.25 GB /foo/barf
598.80 MB /foo/bar/bazf
500.58 MB /bar/bazf
421.70 MB /bar/baz/bamf
...
Run Code Online (Sandbox Code Playgroud)
注意:这必须适用于2.4和2.6,并且应该对输出进行排序.
使用du -h和sort -h
find /your/dir -type f -size +5M -exec du -h '{}' + | sort -hr
Run Code Online (Sandbox Code Playgroud)
说明:
du -h file1 file2 ...打印d ISK ü在圣人^ h给定文件的乌曼可读的格式.sort -hr各种ħ UMAN在可读的数字- [R EVERSE顺序(较大的数字第一).+的find -exec会降低指令的调用次数du,并且因此将加快执行速度.这里+可以替换为';'.您可以删除选项-r的sort,如果你想被打印在最后的大文件的命令.您甚至可以使用更简单的以下命令,但您的终端窗口缓冲区可能会被填充!
find /your/dir -type f -exec du -h '{}' + | sort -h
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想要前十个较大的文件:
find /your/dir -type f -exec du -h '{}' + | sort -hr | head
Run Code Online (Sandbox Code Playgroud)
注:选择-h的sort在大约2009年已经出台,因此该选项可能无法使用旧的发行版(如红帽5).此外,在较旧的发行版(如Red Hat 4)+中find -exec也没有选项.
在老版本,你可以使用xargs,而不是选择+的find -exec.该命令ls还可用于打印已排序的文件.但是为了保证按大小排序,xargs必须ls只调用一次.如果您的文件数量可以接受,则xargs只能调用ls一次:它取决于传递给ls参数的文本长度(所有文件名长度的总和).
find /your/dir -type f -size +5M -print0 | xargs -0 ls -1Ssh
Run Code Online (Sandbox Code Playgroud)
(借用MichaelKrelin-hacker的一点灵感).
说明:
ls -1 每行显示一个文件ls -S 按文件大小排序ls -s 打印文件大小ls -h 以人类可读的格式打印尺寸最快的命令可能是使用上面ls -1Ssh的+选项,find -exec但是如上所述,文件数量必须是可接受的,ls只能调用一次,以保证按大小排序(工作选项+的find -exec方式大致相同xargs).
find /your/dir -type f -size +5M -exec ls -1Ssh '{}' +
Run Code Online (Sandbox Code Playgroud)
为了减少文件的发现的量,可以增加阈值大小:取代+5M通过+100M对实例.
find ... | sort -rn | cut -d\ -f2 | xargs df -h
Run Code Online (Sandbox Code Playgroud)
例如:)或
find $dir -type -f size +$size -print0 | xargs -0 ls -1hsS
Run Code Online (Sandbox Code Playgroud)
(从olibre借来一点灵感).