Home > Mobile >  Substitute values between 2 strings using sed
Substitute values between 2 strings using sed

Time:08-07

I want to replace the value in line number 17 of a kubernetes yaml file dynamically with the AWS account id for ECR. I have written below script to get the value and replace the placeholder {{ACCOUNT}} with the account id using terraform. But I want it to replace value dynamically if after first substitution a different account id is given and not just by matching placeholder {{ACCOUNT}}.

Line to substitute value in: image: {{ACCOUNT}}.dkr.ecr.us-east-1.amazonaws.com/ecr-repo:my-image

I have written below simple substitution sed command, but I am unable to figure out the correct substitution syntax for it to replace not by matching {{ACCOUNT}}, but by replacing whatever characters exist between image: and .dkr .

sed -i '17 s/{{ACCOUNT}}/${data.aws_caller_identity.current.account_id}/g <filename>

CodePudding user response:

If there can not be a dot in the accountId, you can use 2 capture groups:

\(image: \)[^.]*\(\.dkr\.\)
  • \(image: \) Capture group 1, match image:
  • [^.]* Match optional characters other than .
  • \(\.dkr\.\) Capture group 2, match .dkr.

For example:

echo "image: {{ACCOUNT}}.dkr.ecr.us-east-1.amazonaws.com/ecr-repo:my-image" |
sed 's/\(image: \)[^.]*\(\.dkr\.\)/\1[replacement]\2/'

Output

image: [replacement].dkr.ecr.us-east-1.amazonaws.com/ecr-repo:my-image

If there is no second occurrence of .dkr on the same line:

(image: ).*(\.dkr\.)
  • Related