#!/bin/bash # Columniation # $Id: unix5-columniate.sh 191 2006-03-29 11:07:00Z cactus $ # # (C) 2005 Dr. ERDI Gergo # # See http://cactus.rulez.org/elte/2005-1-unix/#5 for a description of what it does # # Licensed under the GNU General Public License, version 2 function help () { self=`basename $0` cat << EOF Usage: $self [FILE] Breaks up the contents of FILE (or the standard input) into columns. Options: -help Shows this help message (C) 2005 Dr. ERDI Gergo Version: \$Id: unix5-columniate.sh 191 2006-03-29 11:07:00Z cactus $ EOF exit 0 } function error () { echo HIBA: $@! >&2 exit 1 } function options () { [ -z "$1" ] && return case "$1" in -help) help ;; *) [ $# -gt 1 ] && error "Too many arguments" [ -f "$1" -a -r "$1" ] || error "$1: Unable to open file" exec <"$1" ;; esac } options "$@" AWKPROG=' BEGIN { width = 0 } { lines[size++] = $0 if (length() > width) width = length() } function height (col_num) { l = size / col_num if (int(l) != l) l = int(l) + 1 return l; } function col_width (col_num, col, max, pos, i) { max = 0 l = height(col_num); for (i = 0; i != l; i++) { pos = i + col * l; if (max < length(lines[pos])) max = length(lines[pos]) } return max; } function sum_width (col_num, sum, i) { if (col_num > size) return sum_width(size) sum = (col_num - 1) * 2; for (i = 0; i != col_num; i++) sum += col_width(col_num, i); return sum; } function cache_widths (col_num, i) { for (i = 0; i != col_num; i++) widths[i] = col_width(col_num, i); } END { # Ha 80-nal szelesebb, akkor nem tordelunk if (width > 80) { for (i = 0; i != size; ++i) print lines[i] exit } for (c = 1; c < 80; c++) if (sum_width(c + 1) > 80) break; l = height(c); cache_widths(c); for (i = 0; i != l; i++) { sor = lines[i]; eddigi_szelesseg = widths[0] + 2; for (j = 1; j != c; ++j) { if ((i + j * l) < size) { format = sprintf("%%-%ds%%s", eddigi_szelesseg) sor = sprintf(format, sor, lines[i + j * l]) eddigi_szelesseg += widths[j] + 2; } } print sor; } } ' awk "$AWKPROG" 2>/dev/null