mguerin
mguerin

Reputation: 344

Replace text in a variable by another variable

I want to replace some text in a variable by another variable.

body='{ "server": {
    "metadata": "metaToReplace"
  }
}'
meta="{
  ARTS_ORACLE_INT_IP: 10.120.47.151,
  ARTS_USER: performance
}"

I tried this, but didn't work:

body=$(echo "${body}" | sed "s|\"metaToReplace\"|${meta}|g")

I got this error :

sed: -e expression #1, char 19: unterminated `s' command

Upvotes: 2

Views: 104

Answers (3)

Jahid
Jahid

Reputation: 22428

You can do this:

meta="$(echo "$meta" |sed ':a;N;s/\n/\\n/;ta;')"
body=$(echo "${body}" | sed "s|\"metaToReplace\"|$meta|g")
echo "$body"

Output:

{ "server": {
    "metadata": {
  ARTS_ORACLE_INT_IP: 10.120.47.151,
  ARTS_USER: performance
}
  }
}

How it works:

echo "$meta" |sed ':a;N;s/\n/\\n/;ta;'

replaces all newlines in meta to leteral \n and thus meta becomes a single line string:

{\n  ARTS_ORACLE_INT_IP: 10.120.47.151,\n  ARTS_USER: performance\n}

which is then used as a replace string and in replacement, \n is interpreted as new line again.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246754

The newlines in the replacement variable are wrecking the syntax of the s/// command:

$ echo "${body}" | sed "s|\"metaToReplace\"|${meta}|g"
sed: -e expression #1, char 19: unterminated `s' command

I'd use awk: You can transfer the contents of the shell variable to an awk variable:

body=$( awk -v rep="$meta" '{gsub(/"metaToReplace"/, rep); print}' <<< "$body" )

Upvotes: 2

Barmar
Barmar

Reputation: 780724

The problem is that the double quotes aren't being put into the body string. Since you started the string with double quotes, the inner quotes are simply matching that and ending the string. Use single quotes around it so that the inner quotes will be treated literally, rather than as delimiters.

body='{ "server": {
    "metadata": "metaToReplace"
  }
}'

Upvotes: 0

Related Questions