How to Find and Replace String with Special Characters Using Sed

bashcommand linelinuxsed

I have a file with content like this:
deployment.yml

spec:
  containers:
  - name: atl-lead
    image: "registry.it.zone/api/dev/atl-x:1.2.0-SNAPSHOT-110"
    imagePullPolicy: Always

I want to use sed command to change this file to:

spec:
  containers:
  - name: atl-lead
    image: "registry.it.zone/api/dev/atl-x:1.8.0"
    imagePullPolicy: Always

I use command below

sed -i "/registry.vn.eit.zone/open-api/dev/atl-x:.*/registry.vn.eit.zone/open-api/dev/atl-x:1.8.0/g" deployment-canary.yml

But it shows this error:

sed: -e expression #1, char 24: unknown command: `o'

Please help me.
Thank you.

Best Answer

You could always escape special symbols to avoid them being treated as regex by prefixing them with a backslash \

In this case it is not necessary, you could simply change the delimiter that sed uses from / to for example % or ! or any other single byte character.

Instead of writing sed 's/search/replace/' you can simply write sed 's%search%replace%'.

Example:

╰─$ echo 'image: "registry.it.zone/api/dev/atl-x:1.2.0-SNAPSHOT-110"' | sed 's%image: "registry.it.zone/api/dev/atl-x:1.2.0-SNAPSHOT-110"%image: "registry.it.zone/api/dev/atl-x:1.8.0"%'

image: "registry.it.zone/api/dev/atl-x:1.8.0"

Tipp: Check out Regex101 if you have problems to create a working regular expression. It will show you each match and error as you type.

Related Question