LuciDroid
LuciDroid

Reputation: 55

How to append string in bash script using sed?

Hello I am trying to make a script to edit chrome flags on mac using a bash script. This script is to set max SSL to TLS1.3 on chrome. However, I am having some issues with sed. Here is what my command looks like:

sed -i '.bak' -e 's/{\"browser\".*origin\":\"\"\}/\"browser\":\{\"enabled_labs_experiments\":\[\"ssl-version-max@2\"\],\"last_redirect_origin\":\"\"\}/g' "./Local State"

The goal is to append

"enabled_labs_experiments":["ssl-version-max@2"]

to this

{"browser":{"last_redirect_origin":""}

to make it looks like this

{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Not sure what's wrong with my command but any help in achieving this is really appreciated or just pointing me in right direction would help greatly.

Thanks!

Upvotes: 3

Views: 291

Answers (3)

dawg
dawg

Reputation: 104102

If you have strings in Bash (versus a file), you may want to use the regex engine in Bash instead of sed to process them in this fashion.

Given:

$ s1='"enabled_labs_experiments":["ssl-version-max@2"]'
$ s2='{"browser":{"last_redirect_origin":""}'

You can split on the first :{ in s2 this way:

$ [[ $s2 =~ (^[^:]+:){(.*$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Or, if you want the same regex as the other answers:

$ [[ $s2 =~ (^{\"browser\":){(\"last_redirect_origin\":\"\"}$) ]] && echo "${BASH_REMATCH[1]}{$s1,${BASH_REMATCH[2]}"
{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204638

You're just throwing backslashes all over the place where they don't belong. Don't do that - learn which characters are metacharacters in regexps and backreference-enabled strings. All you need is:

$ sed 's/\({"browser":\)\(.*origin":""}\)/\1"enabled_labs_experiments":["ssl-version-max@2"],\2/' file
{"browser":"enabled_labs_experiments":["ssl-version-max@2"],{"last_redirect_origin":""}

Upvotes: 0

blackghost
blackghost

Reputation: 1825

sed -i '.bak' -e 's|\(\"browser\"\):{\(\".*origin\":\"\"\)}|\1:{\"enabled_labs_experiments\":[\"ssl-version-max@2\"],\2}|'

The trick is to use the \( and \), to define two groups, and use \1 and \2 in your substitution to represent these groups. BTW, your curly brackets don't match in your examples...

Upvotes: 1

Related Questions