How to use printf to output a shell variable path?

So I created two shell variables: COLUMN1_HEADING, COLUMN2_HEADING.
They have values:

COLUMN1_HEADING="John"
COLUMN2_HEADING="123456789"

How would I use printf to get it to print an output like this:

$COLUMN1_HEADING\t$COLUMN2_HEADING\nJohn\t123456789\n

Thanks!

Hi,

Can you try this and see if this helps?

A=1234;
B=Welcome
printf "%s%s\n" "\$A\t\$B\n$A\t$B\n"

Outputs:

$A\t$B\n1234\tWelcome\n

Hi greet_sed,
That is close, but there is an extra %s in your printf format string. Since there is only one operand to be formatted, only one %s is needed:

A=1234;
B=Welcome
printf "%s\n" "\$A\t\$B\n$A\t$B\n"

produces the same results you showed us above.

Alternatively, you could also try the following (note the difference between using single quotes to avoid parameter expansions instead of escaping the dollar sign inside double quotes in the format operand):

A=1234;
B=Welcome
printf '$A\\t$B\\n%s\\t%s\\n\n' "$A" "$B"

which also produces the same output.

3 Likes

I suppose it depends on what steezuschrist96 actually wanted. Perhaps the output was to include tabs rather than the literal \t characters to line up the output.

To do that, would it be be more of a:-

printf "\$COLUMN1_HEADING\t\$COLUMN2_HEADING\n%s\t%s\n" "$COLUMN1_HEADING" "$COLUMN2_HEADING"

Output is:-

$COLUMN1_HEADING	$COLUMN2_HEADING
John	123456789

The columns don't line up because the literal $COLUMN1_HEADING is so long.

Convert to this to line it up:-

printf "\$COLUMN1_HEADING\t\$COLUMN2_HEADING\n%s\t\t\t%s\n" "$COLUMN1_HEADING" "$COLUMN2_HEADING"

... giving you:-

$COLUMN1_HEADING	$COLUMN2_HEADING
John			123456789

I hope that this help, but apologies if I've got the wrong end of the stick.

Robin