Sed replace line stored in a variable
I need to find a line that starts with mysql.unmetric.twt.url
and replace the entire line with line stored in the variable ip.
ip="mysql.unmetric.twt.url=jdbc:mysql://ec2-a-b-c-d.compute-1.amazonaws.com:3306/unmetric? jdbcCompliantTruncation=false&useUnicode=yes&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true"
How can this be achieved using sed?
There are two stages: first you need to escape any special characters in $ip
:
echo $ip|sed 's#[./&?]#\\&#g'
Then you need to perform the substitution:
sed -i "s/^mysql\.unmetric\.twt\.url.*$/replacement/g" filename
Together these give:
sed -i "s/^mysql\.unmetric\.twt\.url.*$/$(echo $ip|sed 's#[./&?]#\\&#g')/g" filename
Note that the double quotes for the main substitution are important, so that the replacement string will be interpreted.