format columns bash

26 views
Skip to first unread message

mytubeclips

unread,
Jan 26, 2016, 6:10:59 PM1/26/16
to bash tips
Greetings
i have a file which contains the following

Something 01
average max min
123 215 0

Something 02
average max min
1 10 5

etc...

im hoping to change the output to look like:

Something 01
average
123 
max
215 
min
0

Something 02
average

max 
10 
min
5

help please
Thank again.

Don M

unread,
Jan 27, 2016, 11:42:25 PM1/27/16
to bash tips
#!/bin/bash

if [ $# -ne 1 ]
then
    echo Usage: $(basename $0) input_file
    exit 1
fi

if [ ! -r "${1}" ]
then
    echo File ${1} is not readable or does not exist
    exit 2
fi

# redirect file contents into file descriptor 3
exec 3< "$1"

# keep reading lines from file descriptor 3 until no more
while read -u 3 line1
do
    # each set of data covers 4 lines, we already read the first line
    # so read the next three lines
    read -u 3 line2 || MISSING_LINE=1
    read -u 3 line3 || MISSING_LINE=1
    read -u 3 line4 || MISSING_LINE=1

    if [ "${MISSING_LINE}" = "1" ]
    then
        # partial set of data, we expect four rows
        # for each set of data, with the fourth row
        # being blank or just whitespace
        exit 0
    fi

    # parse line2 using whitespace, into field 1, field 2, etc
    set -- $line2
    l2_token1=${1}
    l2_token2=${2}
    l2_token3=${3}

    # parse line3 using whitespace, into field 1, field 2, etc
    set -- $line3
    l3_token1=${1}
    l3_token2=${2}
    l3_token3=${3}

    echo $line1
    echo $l2_token1
    echo $l3_token1
    echo $l2_token2
    echo $l3_token2
    echo $l2_token3
    echo $l3_token3
    echo
done
Reply all
Reply to author
Forward
0 new messages