Last active
May 29, 2025 20:28
-
-
Save xram64/7d5c652c65b6d62f1a716de999755771 to your computer and use it in GitHub Desktop.
Script to sort and print output from `du -sh` Bash command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Script to sort and print output from `du -sh` Bash command | |
| ## xram | 5/29/25 | |
| # -- Output from `du -sh` command ------------------------- | |
| du = """ | |
| 1.2M /bin/bash | |
| 776K /bin/ssh | |
| 7.1M /boot/grub | |
| 97M /lib/gcc | |
| 2.5G /var/log | |
| """ | |
| # --------------------------------------------------------- | |
| from functools import cmp_to_key | |
| # Define comparison-style sort function | |
| def sortfn(a, b): | |
| # Returns 1 if a>b, -1 if a<b, and 0 if a=b | |
| a_val = a.split(' ')[0] | |
| b_val = b.split(' ')[0] | |
| a_mag = a_val[-1] | |
| b_mag = b_val[-1] | |
| m = {'K':1, 'M':2, 'G':3} # magnitude suffixes | |
| if m[a_mag] < m[b_mag]: return -1 # not(a > b) | |
| elif m[a_mag] > m[b_mag]: return 1 # (a > b) | |
| else: | |
| return 1 if float(a_val[:-1]) > float(b_val[:-1]) else -1 | |
| # Split list by lines (ignore empty lines) | |
| du_list = [line for line in du.split('\n') if len(line.strip()) > 1] | |
| # Sort lines | |
| du_list.sort(key=cmp_to_key(sortfn), reverse=True) # translate comparison-style function into key-style function | |
| for line in du_list: | |
| print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment