Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script sorting array of files by size

I want to sort the files in my directory by their size. Currently I have found all the files with a certain extension (ie)*.txt) and then added all the values from that list into my unsorted array. I try to sort all the elements in my array by size, but the "-S" on the last line gives me an error.

list=$(find . -name "*."$1)
unsortedA=()
for x in $list
do
    unsortedA+=($x)
done

sortedA=( $(for arr in "${unsortedA[@]}" 
do
        echo $arr
done | sort -S) ) #This Line Here*

EDIT: All of these lines can be replaced with:

list=$(ls -S *.$1)
like image 628
CarlinLiu Avatar asked Dec 15 '25 05:12

CarlinLiu


1 Answers

Normally, sorting file listings by size is done with:

ls -lS *.$1

In any case, sort -S is meaningless. -S is an option for ls; it means something else to sort. (And that something else is completely irrelevant here.)

If you want just the list of filenames, sorted by filesize, use

ls -S *.$1

and pipe it into whatever you want to use for formatting.

like image 144
rici Avatar answered Dec 16 '25 21:12

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!