2

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
1
  • Please indent code with 4 spaces to enable monospace and syntax highlighting. Commented Jul 14, 2015 at 17:38

3 Answers 3

2

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" )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's working !! I didn't think about newlines :S
0

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"
  }
}'

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.