Reputation: 35
I have a bash script that lists subprograms/processes that could if the user chooses to, insert startupflags to a specific program. I want to match strings in the below formats and depending on which pgm the user chooses I want to insert/replace the string with the new flag infront of {PGMPATH}/pgm. The existing programs are listed in a startupfile according to something like this:
start -existingFlag ${PGMPATH}/pgm
start -existingFlag -anotherExistingFlag ${PGMPATH}/anotherPgm
start -existingFlag -anotherFlag ${PGMPATH}/yetAnotherPgm otherStuff
But to start with I try to match toward a hardcoded string (in the future toward the lines in the startup file):
start -existingFlag ${PGMPATH}\/pgm*
and replace it with a new line looking like this:
*start -existingFlag -newFlag ${PGMPATH}\/pgm*
From script:
existingString="start -existingFlag ${PGMPATH}\/pgm"
newString="start -existingFlag -newFlag ${PGMPATH}\/pgm"
sed 's/$replaceString/$newString/g' $STARTUPCONFFILE
This works (the string is replaced) as long as there is no '$' (just before {PGMPATH}) in the strings, but as soon as I add '$' as in ${PGMPATH} SED doesn't replace. I have tried a lot but I can't get it to work.
Suggestions?
Upvotes: 0
Views: 450
Reputation: 20980
I think, there will be slashes in $PGMPATH. They will interfere with sed syntax.
You can use other character, like | or % as separator, instead of usual /
.
e.g. try:
sed "s|$replaceString|$newString|g"
Alternately, you can use \%regexp%
syntax, given in sed manual here. (I have not used it myself though..)
Another alternate option, is to escape all the slashes in $PGMPATH, using another line of sed; but that would be more difficult.
Also, as pointed to by sudo_O, I have changed the single quote to double quotes, since the variables won't expand, when quoted with single quotes.
Upvotes: 0
Reputation: 85805
You need double quotes for the shell to expand variables:
$ set newString=1
$ set replaceString=one
# using single quotes: no expansion -> no replacement!
$ echo one | sed 's/$replaceString/$newString/g'
one
# using double quotes: expansion -> replacement!
$ echo one | sed "s/$replaceString/$newString/g"
1
Upvotes: 1
Reputation: 72667
What does echo $PATH
print? Are you aware that PATH is usually a colon separated list of directories? Is this really what you want? It would expand to, e.g.
start -existingFlag /usr/bin:/bin:/usr/local/bin/pgm
which is most certainly not what you expect. Maybe you have a variable name clash and should use another name than PATH
.
Upvotes: 0