2

Problem

How do we use variables in a sed edit string?

Example

The file statement.txt is the sentence

I like my pet bird.

Given a variable ${myPet}, how can we use sed to replace bird with the value in ${myPet}?

What doesn't work

sed -ie 's/bird/${myPet}/g' statement.txt

The result is

I like my pet ${myPet}.

dantopa
  • 616
  • 7
  • 19

1 Answers1

7

' single quotes don't expand value of a shell variable so you need to use " double quotes here.

myPet="your_value"
sed -ie "s/bird/${myPet}/g" statement.txt
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93