Reputation: 9700
Is there a way to parse a variable like this AAA=1,BBB=2,CCC=3
in bash and store it to a file in this format?
export AAA=1
export BBB=2
export CCC=3
The reason is that I store the environment variables in AWS Parameter Store and when you do aws ssm get-parameters --names xxx --query "Parameters[0].Value"
you would get a comma-separated string.
Thanks.
Upvotes: 1
Views: 1633
Reputation: 84541
sed
can also be used in this case with 2 substitution expressions. The first to add "export "
at the beginning and the second to replace each ','
with "\nexport "
resulting in the desired output, e.g.
sed 's/^/export /;s/,/\nexport /g'
Example Use/Output
$ echo "AAA=1,BBB=2,CCC=3" | sed 's/^/export /;s/,/\nexport /g'
export AAA=1
export BBB=2
export CCC=3
You can simply redirect to a file to save the results.
awk
You can also do the same thing with awk
, just output each comma-separated field preceded by "export "
, e.g.
awk -F, '{for (i=1;i<=NF;i++)print "export", $i}'
(same result)
Upvotes: 1
Reputation: 39354
export
accepts multiple values in bash, so it is sufficient to just replace the comma with a space, and proceed the line with export:
v=$(aws ssm get-parameters --names xxx --query "Parameters[0].Value")
echo "export ${v//,/ }" > file
Upvotes: 2
Reputation: 1485
Assuming the shell variable "variable" contains AAA=1,BBB=2,CCC=3
, then the following will do what you want:
echo $variable | tr ',' '\n' > filename
The first part echo $variable |
will send the contents of $variable to the stdin of the next process.
The next part tr ',' '\n'
will run a process that converts commas in the stream running from stdin to stdout into newlines.
The last part > filename
will take the stdout from the last part and put it in a file called filename.
Upvotes: 1
Reputation: 69198
Using an array:
v=AAA=1,BBB=2,CCC=3
IFS=, a=( $v )
for i in ${a[@]}
do
echo "export $i"
done > filename
Upvotes: 0