Friday, July 22, 2022

[SOLVED] How to replace a string in a variable with another string in a file using shell script

Issue

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


Solution

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


Answered By - HatLess
Answer Checked By - Senaida (WPSolving Volunteer)