简体   繁体   中英

Print an ordered list of files based on files size in bash

I made the following script to find files based on a 'find' command and then print out the results:

#!/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

...which give me output like:

>>> ./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

What I would like to do first, though, is sort the list by file size before printing it out. What is the best way to go about doing this?

Easy to do if you grab the file size in bytes, just pipe to sort

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

If you wanted to make the file sizes print in MB, you could finally pipe to awk:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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