💾 Archived View for tilde.club › ~filip › tech › script › tsv2txt_table › tsv2txt_table captured on 2024-07-09 at 01:57:32.

View Raw

More Information

⬅️ Previous capture (2022-07-16)

-=-=-=-=-=-=-

#!/bin/bash
set -eu

# FUNCTIONS
print_help(){
    echo "Convert a TSV file to a plaintext table."
    echo "Usage: ./tsv2txt_table.sh <FILE>"
}
get_column_lengths(){
# Input : tsv file
# Output: column lengths
awk '                                                  \
    BEGIN{FS="\t"}                                     \
    {                                                  \
        for(i=1;i<=NF;i++){                            \
            if(clen[i]<length($i)){clen[i]=length($i)} \
        }                                              \
    }                                                  \
    END{                                               \
        for(i=1;i<=length(clen);i++){                  \
            print clen[i]                              \
        }                                              \
    }                                                  \
' "$1"
}
print_txt_table(){
# Input : tsv file, column lengths "c1,c2,..."
# Output: plaintext table
awk -v clen_array="$2" '                          \
    BEGIN{                                        \
        FS="\t";                                  \
        split(clen_array,clen,/,/);               \
        hline="";                                 \
        for(i=1;i<=length(clen);i++){             \
            for(j=1;j<=clen[i]+3;j++){            \
                hline=hline"-"                    \
            }                                     \
        };                                        \
        hline=hline"+";                           \
        hline="+"substr(hline,2);                 \
        print hline                               \
    }                                             \
    {                                             \
        for(i=1;i<=length(clen);i++){             \
            printf "| %s",$i;                     \
            for(j=1;j<=clen[i]-length($i)+1;j++){ \
                printf " "                        \
            }                                     \
        }                                         \
        printf "| \n"                             \
    }                                             \
    END{print hline}                              \
' "$1"
}

# SCRIPT
if [[ -f "$1" ]]; then
    # Get column lengths.
    clen=""
    while read num
    do
        if [[ "$clen" == "" ]]; then
            clen="$num"
        else
            clen="$clen,$num"
        fi
    done < <(get_column_lengths "$1")
    # Print the table.
    print_txt_table "$1" "$clen"
else
    print_help
fi