Skip to content

Instantly share code, notes, and snippets.

@cdosborn
Last active May 13, 2022 23:06
Show Gist options
  • Save cdosborn/563c0e62b050fa95ce22 to your computer and use it in GitHub Desktop.
Save cdosborn/563c0e62b050fa95ce22 to your computer and use it in GitHub Desktop.
pager.awk
#!/usr/local/bin/gawk -f
BEGIN {
for (i in ARGV) {
if (ARGV[i] == "--sep") {
sep = ARGV[i + 1];
"echo \'" sep "\'" | getline sep
}
ARGV[i] = "";
}
}
{
for (i = 1; i <= NF; i++) {
if (field_length[i] < length($i)) {
field_length[i] = length($i);
}
}
lines[NR] = $0;
}
END {
"tput cols" | getline cols
if (!sep) {
longest_line += reduce(field_length, 0, "add");
gaps = length(field_length) - 1
excess = cols - longest_line
sep = sprintf("%-" trunc(excess / gaps) "s", " ")
}
for (l in lines) {
len = split(lines[l], arr, / +/);
for (i = 1; i <= len; i++) {
if (i == len) {
printf "%s", arr[i]
} else {
pad = field_length[i];
printf ("%-" pad "s" sep), arr[i], sep
}
}
print "";
}
}
function reduce(arr, initial, f) {
for (i = 1; i <= length(arr); i++) {
initial = @f(initial, arr[i])
}
return initial;
}
function add(a, b) {
return a + b;
}
function trunc(num) {
return sprintf("%.0f", ((num * 10) - ((num * 10) % 10)) / 10) + 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment