Find and replace match after string in different file from bash script – not working

Issue

I have a string stored in a variable called newOccupation in file2.sh. When I run file2.sh, I would like it to replace whatever is after the word "occupation=" with the string stored in newOccupation.

So in this case, after running the script, occupation="Cashier" should be changed to occupation="Teacher"

I tried to replicate something from a very similar thread here Find and Replace Inside a Text File from a Bash Command
but it doesn’t seem to work. I’m not sure if it’s due to formatting issues from trying to insert a variable instead of a string in the executed command.

file1.txt

name="Bobby"
age="23"
occupation="Cashier"
favoriteColor="Red"

file2.sh

newOccupation="Teacher"
sed -i -e 's/[occupation=]+/"'${newOccupation}'"/g' file1.txt

Solution

Changing your file2.sh:

newOccupation="Teacher"
sed -i "s/occupation=\".*\"/occupation=\"${newOccupation}\"/" file1.txt

Answered By – thezhang

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published