Home > database >  How to replace a string in a variable with another string in a file using shell script
How to replace a string in a variable with another string in a file using shell script

Time:06-04

I want to replace a string with another in shell execustion jenkins.

This works:

sed -i 's/\/opt\/Project\/workspace\/'${PRODUCT}'\/common\/ci_build_Type-'${SUB_PRODUCT}'/\/home\/Projects\/XXX\/'${PRODUCT}'\/common\/ci_build_polyspace_Type-'${SUB_PRODUCT}'/g' polyspaceFiles_${SUB_PRODUCT}_tmp.opts;

But I want to have it like this

#!/bin/sh

WORKSPACE="/opt/Project/jenkins/XX/XX/XX/XX/XXX-XXX"
echo $WORKSPACE
PRODUCT="MyProject"
SUB_PRODUCT="MySubProject"
sed -i 's/'$WORKSPACE'/\/home\/Projects\/XXX\/'$PRODUCT'\/common\/XXX-'$SUB_PRODUCT'/g' polyspaceFiles_$SUB_PRODUCT_tmp.opts;

But it doesn't work.

How can I do That?

Thanks

CodePudding user response:

The default delimiter of sed clashes with the same character's present in your WORKPLACE. As mentioned in the comments, changing the delimiter to a character not present in any of your input or escaping the slashes would work for that issue.

However, you also have a single quoting issue. Not only would you get an error, the variables will not expand.

This sed should work

$ sed -i.bak s"|$WORKSPACE|/home/Projects/XXX/$PASE_PRODUCT/common/XXX-$SUB_PRODUCT|" polyspaceFiles_"$PASE_SUB_PRODUCT"_tmp.opts

CodePudding user response:

You can use characters other than / as delimiter for sed's substitution command.
That way you don't have to escape all the slashes in your paths to avoid syntax breakage.

E.g. you could use ~ as demonstrated below, if you're sure it won't be in any of your paths variables.
(You can also use any of #, %, *, , |, etc. as substitution delimiter. Whatever fits your need. Just make sure all three delimiters used in the s command are the same.)

sed -i 's~'"$WORKSPACE"'~/home/Projects/XXX/'"$PASE_PRODUCT"'/common/XXX-'"$SUB_PRODUCT"'~g' "polyspaceFiles_$PASE_SUB_PRODUCT_tmp.opts";
  • Related