Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - List and Sort Files and Their Sizes and by Name and Size

Tags:

bash

sorting

size


I am trying to figure out how to sort a list of files by name and size.
How do I sort by file name and size using "du -a" and not show directories?

Using "du -a"

1   ./locatedFiles
0   ./testDir/j.smith.c
0   ./testDir/j.smith
1   ./testDir/sampleFunc/arrays
2   ./testDir/sampleFunc
0   ./testDir/j.smith.txt
0   ./testDir/testing
0   ./testDir/test2
0   ./testDir/test3
0   ./testDir/test1
0   ./testDir/first/j.smith
0   ./testDir/first/test
1   ./testDir/first
1   ./testDir/second
1   ./testDir/third
6   ./testDir

How can I list all files without directories, add files sizes, and sort by files name first, then by size?

Thanks for your help

like image 451
jao Avatar asked Mar 18 '12 00:03

jao


2 Answers

You can use this:

find -type f -printf "%f  %s %p\n"|sort

Explanation:

  • -type f to find files only
  • -printf to print the output in specific format:
    • %f to print the file name
    • %s to print the file size
    • %p to print the whole file name (i.e. with leading folders) - you can omit this if you want

Then run through sort which sorts in the order given above (i.e. file name, then file size, then file path). The output would be something like this (part of the output shown):

...
XKBstr.h 18278 ./extensions/XKBstr.h
XlibConf.h 1567 ./XlibConf.h
Xlib.h 99600 ./Xlib.h
Xlibint.h 38897 ./Xlibint.h
Xlocale.h 1643 ./Xlocale.h
xlogo11 219 ./bitmaps/xlogo11
....

Hope this helps

like image 190
icyrock.com Avatar answered Sep 30 '22 17:09

icyrock.com


You can use the sort command

$ find -type f -printf $'%s\t%f\n' | sort -k2,2 -k1,1n

sort by second field(name), then first field(size) numerically.

like image 31
kev Avatar answered Sep 30 '22 19:09

kev