Welcome to Linux Forums! With a comprehensive Linux Forum, information on various types of Linux software and many Linux Reviews articles, we have all the knowledge you need a click away, or accessible via our knowledgeable members.
Find the answer to your Linux question:
Site Navigation
Linux Forums
Linux Articles
Product Showcase
Linux Downloads
Linux Hosting
Free Magazines
Job Board
IRC Chat
RSS Feeds
Free Publications


This is a small bash script I wrote to convert a newline separated list into a columnized list. The column app which is supplied with Linux will do this but you cannot select the number of columns you want. However, it is used as part of this script.

#!/bin/bash
# This is an application to take a list type file (lines) and
# convert each line into a column entry
# Ken Smith <ken.smith1404@gmail.com>

PRGNAME=`basename $0`

usage()
{
cat << EOF

usage: $PRGNAME [options] listfile

This script converts a list from lines into columns.
It simply removes the cr/lf from the end of the line
and then outputs the lines as column data.
It works best with individual words on a line or with
lines of equal length.

OPTIONS:
   -h      Show this message
   -s      Sort
   -u      Unique (implies Sort)
   -C      Unique with Count (implies Sort) 
   -c #    Number of columns (default 5)
EOF
}

SORT_CMD=(cat)
UNIQ_CMD=(cat)
COLMNS=5

while getopts c:Chus OPTION
do
     case $OPTION in
         c)  COLMNS=$OPTARG ;
             ;;
         s)  SORT=1 ;
             ;;
         u)  UNIQ=1 ;
             ;;
         C)  UNIQCNT=1 ;
             ;;
         h)
             usage
             exit 1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

shift $(( OPTIND - 1 ))


# sneaky trick to pick the input from a filename on the command line or from piped data
[[ -z $1 ]] && exec 3<&0 || exec 3<$1


COLMNS=$(($COLMNS-1))

if [[ -n $UNIQCNT ]] 
then 
    SORT_CMD=(sort)
    UNIQ_CMD=(uniq -c)
    UNIQ=
elif [[ -n $UNIQ ]] 
then 
    SORT_CMD=(sort)
    UNIQ_CMD=(uniq)
elif [[ -n $SORT ]] 
then
    SORT_CMD=(sort)
fi

cat <&3 | "${SORT_CMD[@]}" | "${UNIQ_CMD[@]}" | grep -v ^$ | tr 'n' '00' |
 sed -e's/(([^x00]*x00){'$COLMNS'}[^x00]*)x00/1n/g' | tr '00' " " | column -t






Rate This Article: poorexcellent
 
Comments about this article

Comment title: * please do not put your response text here