我正在寻找以下python代码的Bash等效项:
template = 'The {part} on the {vehicle} goes {action} and {action}.'
template.format(part='wheels', vehicle='bus', action='round')
## or ##
vals = {'part': 'wheels', 'vehicle': 'bus', 'action': 'round'}
template.format(**vals)
所需结果:
'The wheels on the bus go round and round.'
bash具有这样的功能吗?如果没有,有没有办法模拟这种行为?
我知道我可以像这样用printf
格式化字符串:
template="The %s on the %s go %s and %s."
part="wheels"
vehicle="bus"
action="round"
printf "${template}" ${part} ${vehicle} ${action} ${action}
## or ##
vals=(${part} ${vehicle} ${action} ${action})
printf "${template}" ${vals[@]}
...但是如果它多次出现在字符串中,就像“动作”一样,我不想多次提供相同的值。
我希望我可以做这样的事情:
declare -A vals=(["part"]="wheels" ["vehicle"]="bus" ["action"]="round")
printf "${template}" ${vals[@]}
我也知道这样的字符串替换:
string="${string//old/new}"
我以为我可以放入一个迭代关联数组并将键替换为值的函数,但是我不能使它起作用主要是因为将关联数组作为参数传递是不平凡的。我敢肯定,最终我会找到一种解决方法,但是该解决方法需要比单纯地忍受printf
的缺点少麻烦。
使用envsubst
,您可以这样做:
template='The ${part} on the ${vehicle} goes ${action} and ${action}.'
part="wheels" vehicle="bus" action="round" envsubst <<< "$template"
或
template='The ${part} on the ${vehicle} goes ${action} and ${action}.'
export part="wheels"
export vehicle="bus"
export action="round"
envsubst '$part $vehicle $action'<<< "$template"