soFan soFan - 3 months ago 10
Bash Question

column formatting for multiline bash variable

I am trying to print a nice and pretty table displaying values of few(3) variables. One of the variable contains multiple line as its content. Which is distorting the format of the table generated.

Tried with

echo -e
first which didn't helped to tried leveraging
printf
but still not able to correct the formatting. Any help is appreciated. Thanks.

var1=10
var2=20
var3=$(cat temp.db) #This is causing issue.

printf "%-10s%-10s%-30s\n" "var1" "var2" "var3"
printf "%-10s%-10s%-30s\n" "$var1" "$var2" "$var3"


where temp.db is structured as follow:

cat temp.db

2 user1
3 user2
5 user3
6 user7
9 user9


Desired output:



var1 var2 var3
10 20 2 user1
3 user2
5 user3
6 user7
9 user9


What I am currently getting:



var1 var2 var3
10 20 2 user1
3 user2
5 user3
6 user7
9 user9

Answer

This sounds like a job for awk-man (a). The following transcript shows it in action:

yup> awk '
...>    BEGIN {
...>        v1 = 10; v2 = 20; f="%-10s %-10s %-30s\n";
...>        printf f, "var1", "var2", "var3";
...>    }
...>    {
...>        printf f, v1, v2, $0;
...>        v1 = ""; v2 = "";
...>    }' inputFile

var1       var2       var3
10         20         2 user1
                      3 user2
                      5 user3
                      6 user7
                      9 user9

Ignore the ...> things, they're my continuation prompt PS2 so I can nicely line up multi-line statements (some of the ; characters are also superfluous but I do that just for consistency).

The code simply sets up the format string and initial values for var1/2, then prints the header in the BEGIN block. Then, for each input line, it outputs your desired columns, formatted as needed.


(a) Think Superman but with less of a square jaw, geekier glasses and probably a pocket protector as well :-)

Comments