Bash - List and Sort Files and Their Sizes and by Name and Size
Solution 1
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
Solution 2
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.
Solution 3
As the other answers so far say, this is not really a bash problem.
du
pretty much insists on telling you about directories: if you point it at a directory, then with or without -a
it will tell you about it.
If you have the GNU du
, though, you can tell it to read a list of NUL-terminated file names from stdin, so you can use find
to produce the list: find ... -print0 | du --files0-from=-
(you don't need the -a
flag here). (If you don't have the --files0-from
option you can still invoke du
relatively efficiently using xargs
; see the xargs
documentation.)
If you have GNU du
, though, you probably have GNU find
, which has -printf
as described by @icyrock.com. Just use that. Then use an explicit sort
.
jao
Developer with BS in CS. Interested in computer security. In my spare time, enjoy outdoors, and working on my Arch Linux system. Dedicated to service Christ with my life :)
Updated on August 07, 2022Comments
-
jao over 1 year
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