by yegle · 4y ago · 0 comments
The "normal" way of doing "count how many times lines are present and list them in decreasing order" is to use a hash table which keeps all the (unique) lines in memory -- so that utility simply wasn't possible when all the standard tools were invented.
~/bin/freq
==========
#! /bin/bash
sort "$@" | uniq -c | sort -nr
Once you get into the habit of capturing your habits as scripts that snap together like German nouns, you'll find the command line a wondrous place. ~/bin/freq
==========
#! /bin/bash
awk '{acc[$0]++} END {for (item in acc) {print acc[item], item}}' | sort -nr $ for x in {0..999}
> do echo $((RANDOM%5))
> done | bar_chart.py -np
# each * represents a count of 8. total 1000
0 [ 193] ************************ (19.30%)
1 [ 200] ************************* (20.00%)
2 [ 209] ************************** (20.90%)
3 [ 193] ************************ (19.30%)
4 [ 205] ************************* (20.50%)
$
[^0]: https://github.com/bitly/data_hacks> it should absolutely never take more than a few milliseconds
Why? It surely depends on your use case (highest possible perf is different for many dupes vs few dupes, for example). And a few milliseconds is lower than a human's ability to respond, so doesn't matter for interactive use, it can only matter in batch scenarios.
sort | uniq | sort -nr takes ~300ms on a file of 10k lines of random data that is 0.5MB on my 10 year old mac. It's ~60ms on 2k lines. It's faster on a newer computer, and unless you're doing this a thousand times in a row, there's next to no difference between 3 ms or 300ms to me in an interactive shell...
BTW, what is the alternative? Are you assuming I write something high performance, spend my time figuring it out? Or is there a higher performance sort|uniq already available?
it's absolutely intolerable
> It's faster on a newer computer, and unless you're doing this a thousand times in a row, there's next to no difference between 3 ms or 300ms to me in an interactive shell...
having to wait 300ms after an interaction makes my hands shake. If the result is not on screen by the time the enter key has gone back up it's plain bad.