I have a config file where i need to replace the entire line with new values. It can be either a word or a URL. I am trying to write a script to replace only this particular parameter with new values.
I have tried using grep
to extract the line using the parameter and divided the values separately and saved in two different variables.
Now I am trying to replace the whole line with the parameter along with new value or url usind sed
jaram=`grep -i "$a" app.properties`; param=`grep -i "$a" app.properties |sed 's/'$a'=*//'`; sed -e 's~'$jaram'~'$a=''$changed_param'~g' app.properties
The config file contains:
abc1=http://howareyou:scema=olk abc2=http://howareyou:scema=olk
Here I am trying to replace the url of only abc1
. though both have same value. I need to replace the entire url with something different url or a word.
Here I am trying to find the line which contains abc1
and this line url after =
is saved in a different variable.
I tried to replace the url with new one using sed:
sed -i 's~'$jaram'~'$a=''$param'~g' app.properties sed: -e expression #1, char 0: no previous regular expression
Seems like I am doing wrong at some syntax when using sed
trying to replace something like
sed 's/jaram/'{$a=$param}/'
Expecting an output like
abc1=http://jalkek:kj/iuwerj abc2=http://howareyou:scema=olk
Advertisement
Answer
The following script with comments:
# recrete the input config file cat <<EOF >input abc1=http://howareyou:scema=olk abc2=http://howareyou:scema=olk EOF # some input variables name="abc1" newvalue='http://jalkek:kj/iuwerj' # the sed script sed -i 's'$'1''^'"$name"'=.*'$'1'"$name"'='"$newvalue"$'x01' input # and the output cat input
produces the following output:
abc1=http://jalkek:kj/iuwerj abc2=http://howareyou:scema=olk
Notes:
- I used the
0x01
byte as the separator fors
command insidesed
. So it should work with all printable characters. - Remember about quoting. All variables should be inside
"
double quotes, but all the rest would be best if inside'
single quotes. - I match the name= with
^
, so from the beginning of the line. So that for exampleblablaabc1=
doesn’t match. - I use ANSI-C Quoting from bash to generate the unredable
0x01
bytes to delimit sed command.
A little more readable version of the sed script could be this one, that just uses "
for quoting and uses ~
as a separator:
sed "s~^${name}=.*~${name}=${newvalue}~"