-1
foo bar, foo bar, foo bar
foo bar

Given this beautiful poem, how could all the bar be replaced by superman, but each time with a different ending, contained in an array (is super, is blazing fast, is marvelous, cawabanga)

So the result would be :

foo superman is super, foo superman is blazing fast, foo superman is marvelous
foo superman cawabanga

I know it is possible to use a for/loop to do so, with sed. But is there a shorter, more beautiful solution?

1

You can do this just with shell parameter expansion: It's really a one-liner

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

I just tried with simple array contents. you can apply the same logic for your question

$ 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
  • 1
    That won't work with spaces in the array elements as in the question, though. – Benjamin W. Sep 10 '18 at 2:51
  • yes.. thats why i asked to implement this logic to OP – Kamaraj Sep 10 '18 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.