Plain text formatting

I recently did some fun shell scripting to format plain text. I found out that Links, a text based browser, is your friend when you want to display a nice table on a terminal screen. Links has some command line options for using it as a filter. More precise, an HTML to plain text filter.
Since it is straight forward convert a CSV file into an HTML table, we’re just one step away from plain text.

The options for links that convert it to a html2text filter are -stdin and -dump. The first option tells it to treat the standard input as HTML code, while the second option makes it spitting out the formatted plain text to stdout.
The following bash function does the trick:

table() {
        FIELD_SEPARATOR=$1
        awk -F"$FIELD_SEPARATOR" '
        BEGIN { print "<table border=0>" } {
                x=1
                print"<tr valign=top>"
                while ( x < = NF ) {
                        if ( x == 1) print "\t <td align=right>" $x ""
                                else print  "\t <td>" $x "</td>"
                                ++x
                }
                print "</tr>"
        }
        END {
                print "</table>"
        }' | links -stdin -dump -dump-width 83 |  sed 's/^   //'
}

Now you can simply apply the filter using:

$ cat file.csv | table ","

Comments are closed.