nass
nass

Reputation: 1495

How to print text with a placeholder replaced by a value from a variable in Bash?

I am not sure I even state this properly.

Here is what I have in a bash script

ATEXT="this is a number ${i} inside a text string"

then I want ${i} to be resolved during the following for loop.

for i in {1..3}; do
    echo "${ATEXT}"
done

Of course the above does not work because i is resolved when the variable ATEXT is read.

However, I do not know how to achieve what I want. which is to get the output:

this is a number 1 inside a text string
this is a number 2 inside a text string
this is a number 3 inside a text string

Upvotes: 2

Views: 302

Answers (2)

chepner
chepner

Reputation: 532053

For parameterized text, use printf, not echo:

ATEXT="this is a number %d inside a text string"
for i in {1..3}; do
    printf "$ATEXT\n" "$i"
done

See also:

Upvotes: 7

Saucier
Saucier

Reputation: 4370

Probably I would prefer @chepner's answer - but as a good alternative you could also do the following:

$ cat script
#!/usr/bin/env bash

_aText()
{
    printf "this is a number %d inside a text string\n" $1
}

for i in {1..3}; do
    _aText $i
done

$ ./script
this is a number 1 inside a text string
this is a number 2 inside a text string
this is a number 3 inside a text string

Upvotes: 5

Related Questions