在 bash 中读取文件时,我必须创建多个变量。这些变量需要根据文件内容具有动态名称。例如:
文件内容:
abc: 20
1 apple a day
abc: 40
1 keeps the doctor away
现在我必须将变量创建为:
day_20_id = 1
day_20_fruit = apple
away_40_id = 1
away_40_who = doctor
就像在所有变量名中一样,只有 的值$abc
会被更新,变量的值将与文件内容一致。
有人可以帮我弄清楚如何实现这一目标。
您可以使用 eval 命令来完成此操作,如下所示
abc=20 # assuming you got this from the input file
val=1 # assuming you also got this from the input file
varName="day_${abc}_id"
command="${varName}=${val}"
eval $command
# now print to output file as you have stated in the comments
outputFile=output.txt # randomly-chosen name
command="echo $varName = $val > $outputFile"
eval $command
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句