如何使用占位符替换为Bash中变量的值来打印文本?

nas*_*ass 2 bash

我不确定我是否正确说明了这一点.

这是我在bash脚本中的内容

ATEXT="this is a number ${i} inside a text string"
Run Code Online (Sandbox Code Playgroud)

然后我希望${i}在以下for循环中解决.

for i in {1..3}; do
    echo "${ATEXT}"
done
Run Code Online (Sandbox Code Playgroud)

当然上面的方法不起作用,因为iATEXT读取变量时会解析.

但是,我不知道如何实现我想要的.这是获得输出:

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
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

对于参数化文本,请使用printf,而不是echo:

ATEXT="this is a number %d inside a text string"
for i in {1..3}; do
    printf "$ATEXT\n" "$i"
done
Run Code Online (Sandbox Code Playgroud)

也可以看看:


Sau*_*ier 5

可能我更喜欢@Chepner的答案 - 但作为一个很好的选择,你也可以做以下事情:

$ 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
Run Code Online (Sandbox Code Playgroud)