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