7

Instead of the following

printf '%s\t%s\t%s\t%s\n' 'index' 'podcast' 'website' 'YouTube'

I want to store the printf output in a Results variable, how can I do this?

2
  • 1
    "store formatting string in a variable" - that's what you're doing already with Row='%s\t%s\t%s\t%s\n', so I guess you want to store the output of printf? In the same Row variable?
    – kos
    Commented May 9, 2024 at 15:42
  • 3
    Does this answer your question? How can I assign the output of a command to a shell variable?
    – kos
    Commented May 9, 2024 at 15:45

1 Answer 1

16

Bash (since 3.1), zsh (since 5.3) and ksh93 (since v- and u+m 2021-11-28) have an "assignment to variable option" for printf:

$ Row='%s\t%s\t%s\t%s\n'
$ printf -v Result -- "${Row}" 'index' 'podcast' 'website' 'YouTube'
$ echo "${Result}"
index   podcast website YouTube

$ 

Notice I get two newlines -- one from the printf format, the other from the echo.

You could also control the column widths using something like $-10s for each field, instead of tabbing.

The advantage of this over the $( ... ) or `back-quote` syntax, in addition to preserving trailing newlines is that it does not need to run a subshell for the assignment which in shells other than ksh93¹ is relatively costly.


¹ It's less costly in ksh93 where it doesn't involve a fork but can be made even less so there with the ${ printf...; } form of substitution. That one will be supported in the next version of bash after 5.2.x as well as the next version of zsh after 5.9.x as well as the ${|...} variant from mksh

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.