I have ./cpptest.sh to which I am passing a command line parameter
For e.g.
$./testcps.sh /srv/repository/Software/Wind_1.0.2/
The above command line parameter, is stored in variable $1 when I echo $1, the output is correct (the path)
Actual issue... There is another file let's say abc.properties file. In this file there is a key-value field something like location.1=stg_area. I want to replace the 'stg_area' with the value stored in $1 (the path) so that the substitution looks like location.1=/srv/repository/Software/Wind_1.0.2/
Now, to achieve this, I am tried all option below with sed and none worked
sed -i "s/stg_area/$1/" /srv/ppc/abc.properties
//output is sed: -e expression #1, char 17: unknown option to `s'
sed -i 's/stg_area/'"$1'"/' /srv/ppc/abc.properties
//output is sed: -e expression #1, char 18: unknown option to `s'
sed -i s/stg_area/$1/ /srv/ppc/abc.properties
//output is sed: -e expression #1, char 17: unknown option to `s'
I think I have tried all possible ways... Any answer on this is appreciated. Thanks in advance.
CodePudding user response:
You know that sed
is using /
as a special separator in the command s/pattern/replacement/
, right? You've used it yourself in the question.
So obviously there's a problem when you have a replacement string containing /
, like yours does.
As the documentation says:
The
/
characters may be uniformly replaced by any other single character within any givens
command. The/
character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a\
character.
So the two available solutions are:
use a different separator for the
s
command, such ass#stg_area#$1#
(although you still need to check there are no
#
characters in the replacement string)sanitize the replacement string so it doesn't contain any special characters (either
/
, or sequences like\1
, or anything else sed treats as special), for example by escaping them with\
sanitized=$(sed 's#/#\\/#g' <<< $1)
(and then used
$sanitized
instead of$1
your sed script)
CodePudding user response:
Many thanks @Useless (the person who helped me). Your suggestions of using set -x and using alternate separators solved the issue.
Summary:
when you store a variable with a path info like $1=/srv/repository/Software/wind and want to substitute the this variable in your sed command then use alternate separators like #. Now this to avoid messing up with compiler and giving clear instructions.
initially my sed command was like sed -i "s/stg_area/$1/" /srv/ppc/abc.properties
I replaced it with sed -i "s#stg_area#$1#" /srv/ppc/abc.properties and this worked like a charm.