config

OpenBSD system configuration
git clone git://jacobedwards.org/config
Log | Files | Refs | README

commit 9c17fecc04ba5928d751f9a9f3fe27c9c9f06bba
parent 6962f1ebd17c7a4d92641dba4994503a9286581b
Author: Jacob R. Edwards <n/a>
Date:   Mon, 28 Nov 2022 21:37:05 -0600

Allow human.awk to work in reverse

The application for this might not be immediately apparent, but it
can be used to allow any numerical-wise program to work on binary
prefixed values aswell, which can be very useful as you'll see in
the next commit.

Diffstat:
Mlocal/bin/bin/human.awk | 22++++++++++++++++++++--
1 file changed, 20 insertions(+), 2 deletions(-)

diff --git a/local/bin/bin/human.awk b/local/bin/bin/human.awk @@ -8,11 +8,13 @@ # units), try and shorten it as much as possible while still keeping # it at or above 1 by by using larger units. # +# It will work in reverse if you pass 'undo' as an argument. +# # NOTE: Perhaps instead of using awk fields, I should extract the # first "word" (non-space byte sequence), process it with humanize(), # and insert it into the same place, thus preserving whitespace. -function humanize(bytes, _, i, start) +function humanize(bytes, reverse, _, i, start) { # Not needed right now, but could be with other applications #if (!match(bytes, bytereg)) @@ -22,11 +24,18 @@ function humanize(bytes, _, i, start) start = 0; } else { start = numbers[substr(bytes, RSTART, 1)]; + # Not strictly needed (regex verifies), yet I feel it's best if (!start) return bytes; bytes = substr(bytes, 1, RSTART); } + if (reverse) { + for (i = start; i; --i) + bytes = bytes * base; + return sprintf("%d", bytes); + } + for (i = start; bytes >= base && (!i || letters[i]); ++i) bytes = bytes / base; return i ? sprintf("%.1f%s%s", bytes, letters[i], type) : bytes; @@ -48,10 +57,19 @@ BEGIN { # Cache regexes suffixreg = sprintf("[%s%s](%s)?", toupper(suffixes), tolower(suffixes), type); bytereg = sprintf("[0-9]+(%s)?", suffixreg); + + if (ARGC == 2 && ARGV[1] == "undo") { + delete ARGV[1]; + --ARGC; + undo = 1 + } else if (ARGC > 1) { + print "usage: human.awk [undo]" > "/dev/stderr"; + exit 1 + } } { if (match($1, bytereg)) - $1 = humanize($1); + $1 = humanize($1, undo); print; }