如何按文件大小对 find 命令的结果进行排序?
我尝试对这个 find 命令的结果进行排序:
find ./src -type f -print0
我不需要目录的大小,我需要仅按大小排序的文件相对路径。
以下是如何使用find
命令:
find . -type f -exec ls -al {} \; | sort -k 5 -n | sed 's/ \+/\t/g' | cut -f 9
这是如何执行
使用递归ls
命令:
ls -lSR | sort -k 5 -n
或者,如果您只想显示文件名:
ls -lSR | sort -k 5 -n | sed 's/ \+/\t/g' | cut -f 9
ls
按文件大小排序文件路径:
find src -type f -printf '%s\t%p\n' | sort -n | cut -f2-
备注:
sort -n
更改为
sort -nr
以获得相反的顺序
-print0
,但迎合包含换行符的文件名似乎很迂腐。
%p
改为
%P
就会得到
src/
下的相对路径
find -type f -exec du -sm {} \; | sort -nk1
大小以 MiB 为单位,路径是相对的。
find /folder -type f -exec ls -S {} +
警告!我用的不是-exec ... \;
,而是
-exec ... {} +
。这种结构不会只提取找到的每个文件,而是等待,直到找到所有文件,然后将它们作为一大参数列表放入一个命令(这次 -
ls
)。 然后
ls
正在查看文件,并且因为
-S
键,按大小对它们进行排序,最大的在前。
find -type f -printf '%s %p\n' | numfmt --to=iec | sort -h
这是我做的。
#!/bin/bash
################# ls-by-min ################
## List By Min File Size ##
## Copyright (c) 2020 Theodore R. Smith ##
## License: MIT ##
if [ -z "$1" ]; then
echo "Error: You must specify a minimum file size (in MB)."
exit 1
fi
FILE_SIZE=$1
if [ "$2" = "-r" ]; then
MAXDEPTH=512
else
MAXDEPTH=1
fi
find . -maxdepth ${MAXDEPTH} -type f -size "+${FILE_SIZE}M" -exec du -sm {} \; | sort -rnk1 | sed 's/^[0-9]\+\t*//g'
https://github.com/hopeseekr/BashScripts/blob/master/ls-by-min
你可以通过以下方式运行它:
ls-by-min 100 [-r]
并且它将按从大到小的顺序列出当前目录中仅 100 MB 或更大的文件。传入 -r
使其递归。