How to use variable in sed command to replace a property value in a property file

StackOverflow https://stackoverflow.com/questions/23169174

  •  06-07-2023
  •  | 
  •  

سؤال

i can able to use the below command to change value of target by means of hard coding.

sed -ie s/^target=.*/target=google.com/ url.properties

But if i used variable i am getting error. I dont know how sed commands all working. I only needed to set build system thats it.

url = google.com
sed -ie s/^target=.*/target=$url/ url.properties

the error is sed: -e expression #1, char 25: unterminated `s' command

هل كانت مفيدة؟

المحلول

The problem may be happening because your URL may contain / which bash interprets as sed syntax, so something like https/www.google.com ends up something like :

sed -ie 's/^target=.*/target=https/www.google.com/' url.properties

I will suggest to delimit any special characters to avoid sed to be confused :

url=google.com
url=`echo $url | sed -e "s/\//\\\\\\\\\//g"` # delimits backslash in URL's
sed -ie "s/^target=.*/target=$url/" url.properties

نصائح أخرى

Two problems:

  • You can't have spaces in variable assignments in bash
  • You must quote the sed command (and ideally the url too)

Working example:

url="google.com"
sed -ie "s/^target=.*/target=$url/" url.properties
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top