-
-
Save shello/1013301 to your computer and use it in GitHub Desktop.
Short script for sorting 'du' output correctly. meqif did it in both Ruby and Python as practice; I perfected the python version.
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
#!/usr/bin/env python | |
import sys | |
UNIT_FACTORS = {'B': 0, 'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5} | |
def bytes_multiplier(unit): | |
if UNIT_FACTORS.has_key(unit): | |
return 1024 ** UNIT_FACTORS[unit] | |
else: | |
return 1 # Do not alter values with unknown units. | |
def sort_criterion(line): | |
weight = line.split()[0] | |
unit = weight[-1] if weight[-1].isalpha() else "" | |
size = weight[:-1] if unit != "" else weight | |
# some locales use commas as decimal separators | |
size = size.replace(",", ".") | |
# return the value in bytes | |
return float(size) * bytes_multiplier(unit) | |
INPUT_FILE = sys.stdin | |
input = INPUT_FILE.readlines() | |
ordered_data = sorted(input, key=sort_criterion) | |
for line in ordered_data: | |
print line.rstrip() |
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
#!/usr/bin/env ruby | |
INPUT_FILE = STDIN | |
input = INPUT_FILE.readlines | |
ordered_data = input.sort_by do |line| | |
size = line.split.first | |
# some locales use commas as decimal separators | |
size.sub!(",", ".") | |
case size[-1] | |
when "B" | |
size = size.to_f | |
when "K" | |
size = size.to_f * 1024 | |
when "M" | |
size = size.to_f * 1024**2 | |
when "G" | |
size = size.to_f * 1024**3 | |
else # size given in blocks, don't mess with it | |
size = size.to_f | |
end | |
end | |
puts ordered_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment