#!/bin/bash ### min-expand.sh --- Minimal column-width expand command. ## Copyright (C) 2007 Aaron S. Hawley ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ## $Id: min-expand,v 1.4 2007/07/19 20:42:33 aaronh Exp $ ### Commentary ## Takes a tab-delimited file on standard input and outputs with only ## the minimal number of spaces between columns. The are properly ## aligned, but as narrowly as is possible. ## First it reads the entire file and determines the maximum width of ## each column, then determines the proper 'tab stops', then runs the ## file through expand with the tab stop settintgs. ## Any command-line arguments passed to this script are sent to the ## cut command before maximum column widths are calculated. However, ## the output of this command will contain all the columns. ### Example: ## $ EXAMPLE="First\tLast\tBirth year\tKOs\nEvander\tHolyfield\t1962\t27\n\ ## Jack\tDempsey\t1895\t51\nJoe\tLouis\t1914\t55\nMuhammad\tAli\t1942\t37" ## $ echo -e "${EXAMPLE}" ## First Last Birth year KOs ## Evander Holyfield 1962 27 ## Jack Dempsey 1895 51 ## Joe Louis 1914 55 ## Muhammad Ali 1942 37 ## $ echo -e "${EXAMPLE}" | min-expand ## First Last Birth year KOs ## Evander Holyfield 1962 27 ## Jack Dempsey 1895 51 ## Joe Louis 1914 55 ## Muhammad Ali 1942 37 ### Code: ## Awk script that calculates the tab stop widths. # First written for GNU Awk 3.1.5 SOURCE="\ BEGIN { \ FS = \"\\t\"; \ min_space = 1; \ } \ \ { \ for (i = 1; i < NF; i++) { \ field_size = length(\$i); \ if (width[i] < field_size) { \ width[i] = field_size; \ } \ } \ } \ \ END { \ tabstop = tabstops = width[1] + min_space; \ for (field = 2; field <= length(width); field++) { \ tabstop += width[field] + min_space; \ tabstops = tabstops \",\" tabstop; \ } \ print tabstops; \ } \ "; TMPFILE=/tmp/min-expand.$$ if [ -z "$*" ] || [ $# = 0 ]; then TABSTOPS=`tee "${TMPFILE}" | awk "${SOURCE}"`; else TABSTOPS=`tee "${TMPFILE}" | cut "$*" | awk "${SOURCE}"`; fi expand -t"${TABSTOPS}" "${TMPFILE}" rm -f "${TMPFILE}" ### End of file