1

I can order a list of files / directories by size:

ls -lS 

But if I am using du in human readable format:

du --max-depth=1 -h . 

I get:

128K ./something 3,3M ./more 3,2M ./even-more ... 

Which is not ordered. Is there any standard tool to order this kind of data? Standard sort does not seem to support this. Do I need to roll my own?

4
  • GNU sort has sort -h (note that your --max-depth=1 is GNU-specific already) Commented Jul 26, 2018 at 9:13
  • Thanks, that's it. Not sure how I missed that ... :( Commented Jul 26, 2018 at 9:18
  • These is no standard tool that does this. Commented Jul 26, 2018 at 9:21
  • ... which isn’t a problem because -h isn’t a standard option for du either ;-). Commented Jul 26, 2018 at 9:33

2 Answers 2

7

GNU sort has a -h/--human-numeric-sort option and h sort key flag to handle those (it expects 1024-based units (1023 sorts before 1K) which happens to be how GNU du counts as well.

Now note that some precision is lost when you use du -h, so the order may end-up being wrong:

$ du -k a b 1212 a 1208 b $ du -h a b | sort -h 1.2M a 1.2M b 

As mentioned by @StephenKitt, you can work around it by telling du to give you the full precision and only convert to human format after sorting using for instance GNU numfmt:

$ du --block-size=1 a b | sort -n | numfmt --to=iec 1.2M b 1.2M a 

(beware that spacing is affected). All of the above assume file names don't contain newline characters.

As for the generic question about ordering by size, zsh globs have a oL glob qualifier for that (note that it's by size, not disk usage).

ls -S could be done (with GNU ls for its -U for unsorted):

ls -ldU -- *(oL) 

For sorting by size after symlink resolution:

ls -LldU -- *(-oL) wc -c -- *(-oL) 
0
0

The GNU variants of ls and sort understand -h (mnemonic: -human). You can either use ls -lSh, ls -sSh or du -h … | sort -h:

du --max-depth=1 -h . | sort -h 

Keep in mind that ls won't report the size for directory contents.

2
  • ls does report the correct size for directories... But a directory’s size isn’t the size of the files it contains. Commented Jul 26, 2018 at 9:37
  • @StephenKitt That's what I meant, I'll try to rewrite it. Commented Jul 26, 2018 at 9:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.