A better way to manipulate text

Good morning everyone,

I'm currently trying to convert an environment variable into a string and then attach it at the end of a command and launch it.

I have the following right now, but it's very ugly:

AMI_TAGS="env=test,country=XX,city=blah,galaxy=blahblah"

aws ec2 create-tags --resources ami-1234 --tags $(echo "${AMI_TAGS}" | \
  tr ',' '\n'|sed -e 's/=/ /g' | while read key val; do \
  echo Key=$key Value=$val;done | tr ' ' ',' | tr '\n' ' ')

Output is:

aws ec2 create-tags --resources ami-1234 --tags Key=env,Value=test Key=country,Value=XX Key=city,Value=blah Key=galaxy,Value=blahblah

Here is the man:create-tags � AWS CLI 1.16.9 Command Reference

I could do a cleaner for loop but then I would launch 1x "aws ec2" command for each string. I would prefer avoiding that.

I'm currently reading about the "set" command for bash but I would appreciate some guidance or input or an example here.

Thank you in advance and I hope I've properly explained what's needed.

Not sure I fully understand your request, but how far would this (using shell expansions only) get you:

AMI_TAGS="env=test,country=XX,city=blah,galaxy=blahblah"
AMI_TAGS="${AMI_TAGS//,/ Key#}"
AMI_TAGS="Key=${AMI_TAGS//=/,Value=}"
aws ec2 create-tags --resources ami-1234 --tags "${AMI_TAGS//#/=}"
1 Like

damn, that worked.

thank you very much.

now if I may ask, I can come very close ti the same result with:

sed -e 's/,/ Key#/g' -e 's/=/,Value=/g' -e 's/#/=/g'

but the first value "env" in this case, is missing the "Key=" in front if it. How does the shell expansion does it?

By just adding the Key= string in front:

AMI_TAGS="Key=${AMI_TAGS//=/,Value=}"

You could do so in sed by adding the substitution s/^/Key=/ . But: using sed in a "command substitution" requires an expensive process creation, while variable expansion is done within the shell only.

One question, would it be possible to get the output without the single quotes?

currently getting:

aws ec2 create-tags --resources ami-1234 --tags 'Key=env,Value=xxx Key=city,Value=xxx Key=country,Value=xxx'

I don't really understand where they are inserted.

When and how do you see the single quotes?

#!/bin/bash

AMI_TAGS="env=prod,city=xxx,country=XXX"

AMI_TAGS="${AMI_TAGS//,/ Key#}"
AMI_TAGS="Key=${AMI_TAGS//=/,Value=}"
aws ec2 create-tags --resources ami-1234 --tags "${AMI_TAGS//#/=}"

Executing with "bash -x" gets:

+ AMI_TAGS=env=xxx,city=xxx,country=XXX
+ AMI_TAGS='env=xxx Key#city=xxx Key#country=XXX'
+ AMI_TAGS='Key=env,Value=xxx Key#city,Value=xxx Key#country,Value=XXX'
+ aws ec2 create-tags --resources ami-1234 --tags 'Key=env,Value=prod Key=city,Value=xxx Key=country,Value=XXX'

Notice the single quotes after the "--tags" keywork. Weirdly enough, amazon doesn't accept this format and the tags are not being set.

Try leaving out the double quotes around the AMI_TAGS expansion.

yep, that was it. Thank you very much!