File: bully.awk 1 #!/usr/bin/awk -f 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2020-2025 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 # bully 27 # Tally input lines, also showing bullets for the tally count 28 # 29 # 30 # Show a reverse-sorted tally of all lines read, where ties are sorted 31 # alphabetically. In addition, a 3rd column with bullets helps you 32 # instinctively grasp tallies as quantities relative to each other. 33 # 34 # High tally counts will show a lot of bullets, of course, which isn't 35 # helpful: the regular tally script is better, in those cases. 36 # 37 # Output is a 3-item TSV table, which starts with a header line. 38 39 40 BEGIN { print "value\ttally\tbullets" } 41 42 { tally[$0]++ } 43 44 END { 45 # find the max tally, which is needed to build the bullets-string 46 max = 0 47 for (k in tally) { 48 if (max < tally[k]) max = tally[k] 49 } 50 51 # make enough bullets for all tallies: this loop makes growing the 52 # string a task with complexity O(n * log n), instead of a naive 53 # O(n**2), which can slow-down things when tallies are high enough 54 bullet = "•" 55 bullets = bullet 56 for (n = max; n > 1; n /= 2) { 57 bullets = bullets bullets 58 } 59 60 # the sort cmd to use for the final output, along with its options 61 sortcmd = "sort -t '\t' -rnk2 -k1d" 62 63 # emit unsorted output lines to the sort cmd, which will emit the 64 # final reverse-sorted tally lines 65 for (k in tally) { 66 t = tally[k] 67 s = (t == 1) ? bullet : substr(bullets, 1, t) 68 printf "%s\t%d\t%s\n", k, t, s | sortcmd 69 } 70 }