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
Advertisement
Answer
Changing your file2.sh:
newOccupation="Teacher" sed -i "s/occupation=".*"/occupation="${newOccupation}"/" file1.txt