![用数组中包含的内容迭代替换](https://linux22.com/image/139851/%E7%94%A8%E6%95%B0%E7%BB%84%E4%B8%AD%E5%8C%85%E5%90%AB%E7%9A%84%E5%86%85%E5%AE%B9%E8%BF%AD%E4%BB%A3%E6%9B%BF%E6%8D%A2.png)
foo bar, foo bar, foo bar
foo bar
鉴于这首美丽的诗,怎么可能全部都bar
被替换superman
,但每次都有不同的结局,包含在一个数组中(is super, is blazing fast, is marvelous, cawabanga)
所以结果是:
foo superman is super, foo superman is blazing fast, foo superman is marvelous
foo superman cawabanga
我知道可以使用 for/loop 和 sed 来执行此操作。但有没有更短、更美观的解决方案呢?
答案1
您只需通过 shell 参数扩展即可做到这一点:这确实是一句简单的话
poem='foo bar, foo bar, foo bar
foo bar'
traits=( "is super" "is blazing fast" "is marvelous" "cawabanga" )
for trait in "${traits[@]}"; do poem=${poem/bar/"superman $trait"}; done
echo "$poem"
foo superman is super, foo superman is blazing fast, foo superman is marvelous
foo superman cawabanga
答案2
我只是尝试使用简单的数组内容。你可以对你的问题应用相同的逻辑
$ declare -a var=(A B C D)
$ cat test.txt
foo bar, foo bar, foo bar
foo bar
$ awk -vArr="${var[*]}" 'BEGIN {split(Arr,awk_arr," ")}{for(i=1;i<=NF;i++)if($i~/bar/){count++;$i=awk_arr[count]}}1' test.txt
foo A foo B foo C
foo D