banjocode Replace Text or a String in Bash

Replace Text or a String in Bash

Sometimes you might need to replace some text in a string - the bash allows you to do so easily. This is a short summary on how you can do that.

3 min read

Replacing a String

Replacing a string in Bash can be done in several different ways. The two most common are bash string manipulation as well as sed. Here are some ways you can do that.

The example we want to change is like this:

sentence        =   "This is the first sentence."
old             =   "first"
new             =   "second"
expected        =   "This is the second sentence."

So basically, we want to make this transformation:

"This is the first sentence." => "This is the second sentence."

Using Bash String Manipulation

In this method, you need to sentence to be a variable, like above. You cannot pass only a string. Both echo produces the same successful result.

sentence="This is the first sentence."
old="first"
new="second"

# replace first occurance
echo "${sentence/first/second}"     # with normal strings
echo "${sentence/${old}/${new}}"    # with variables

# replace all occurences
echo "${sentence//first/second}"     # with normal strings
echo "${sentence//${old}/${new}}"    # with variables

Using Sed

Using sed is not much unlike above, however, the syntax is a little bit different. And it is way more customizable. I would recommend sed when working with files and the bash string manipulation for variables.

The -i flag in the command means that we replace the original file.

sentence="This is the first sentence."
sentenceFile=sentence.txt
old="first"
new="second"

# variables
sed 's/first/second/g' <<<"This is the first sentence"
sed "s/${old}/${new}/g" <<<"$sentence"

# file
sed -i 's/first/second/g'  sentence.txt
sed -i "s/${old}/${new}/g" "$sentenceFile"

# alternative way if your strings/variables includes '/'
sed -i "s|${old}|${new}|g" "$sentenceFile"
sed -i "s:${old}:${new}:g" "$sentenceFile"

# replace only first occurance if multiple
sed -i "s/${old}/${new}/" "$sentenceFile"

Notice that we use "" syntax to be able to use variables in commands, while '' only allow for strings.

You can change your separator (/ as standard) if your string includes it. You could use : or | instead. Also, the g stands for global and changes all occurences. If you omit that, only the first word will be replaced.