sed for replacting special characters with ""

Viewed 106

I try to parse the output of terraform output like this:

terraform output -json all_admins |
sed -e "s/,/;\n/g" -e "s/^(\[|\])//g"
terraform output -json all_admins

leads to:

["admin1@admin.com","admin2@admin.com"]

Current result:

terraform output -json all_admins |
sed -e "s/,/;\n/g" -e "s/^(\[|\])//g"

leads to:

["admin1@admin.com";
"admin2@admin.com"]

Exptected result:

"admin1@admin.com";
"admin2@admin.com"

How can I elegantly get rid off [ and ] with a regex in sed?

2 Answers

You may use:

terraform output -json all_admins | sed 's/[][]//g; s/,/;\
/g'

# Example:
s='["admin1@admin.com","admin2@admin.com"]'
echo "$s" | sed 's/[][]//g; s/,/;\
/g'

"admin1@admin.com";
"admin2@admin.com"

Make sure an unescaped ] is placed at 1st position inside bracket position [...] and [ is next.

Note that sed 's/[][]//g' file is equivalent of sed -E 's/\]|\[//g' file

With your shown samples only, could you please try following. Written and tested with GNU awk.

terraform output -json all_admins | 
awk -v RS='\\[|,|\\]' 'NF{$0=$0(RT==","?";":"");print}'

With shown samples output will be as follows.

"admin1@admin.com";
"admin2@admin.com"

Explanation: Setting RS(record separator) as [,] for all lines. Then in main program checking condition if number of fields is NOT NULL and RT is , add ; to current line else keep line same as it is, finally print the current line.

Related