根据bash中的文件大小打印有序的文件列表

时间:2015-03-25 15:48:18

标签: bash

我制作了以下脚本,根据'find'命令查找文件,然后打印出结果:

#!/bin/bash
loc_to_look='./'

file_list=$(find $loc_to_look -type f -name "*.txt" -size +5M)

total_size=`du -ch $file_list | tail -1 | cut -f 1`

echo 'total size of all files is: '$total_size

for file in $file_list; do
    size_of_file=`du -h $file | cut -f 1`
    echo $file" "$size_of_file
done

...给我的输出如下:

>>> ./file_01.txt 12.0M
>>> ./file_04.txt 24.0M
>>> ./file_06.txt 6.0M
>>> ./file_02.txt 6.2M
>>> ./file_07.txt 84.0M
>>> ./file_09.txt 55.0M
>>> ./file_10.txt 96.0M

然而,我首先想要做的是在打印之前按文件大小排序。这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

如果你以字节为单位获取文件大小,只需输入sort

即可轻松完成
find $loc_to_look -type f -name "*.txt" -size +5M -printf "%f %s\n" | sort -n -k 2

如果你想以MB为单位打印文件大小,你最终可以输入awk:

find $loc_to_look -type f -printf "%f %s\n" | sort -n -k 2 | awk '{ printf "%s %.1fM\n", $1, $2/1024/1024}'
相关问题