sam
sam

Reputation: 655

Regex to replace a string with special characters in shell

I have text file called sample.txt which contains

name="sam:18"

I want this to be replaced with the name given in configuration file which is called name.config which has

name="robin:19"

Here is my script which is called nameReplace.sh:

#!/bin/bash
source name.config
sed -i -e 's/name=[A-Za-z0-9]*/name=${name}/g' sample.txt

This executes but doesn't give any change in sample.txt.

I want the following output in sample.txt:

name="robin:19"

Please any help?Thanks

Upvotes: 1

Views: 154

Answers (1)

anubhava
anubhava

Reputation: 785611

Your regex:

name=[A-Za-z0-9]*

won't match:

name="sam:18"

Change your sed to:

sed -i.bak "s/name=.*/name=\"${name}\"/" sample.txt

Using double quotes here to be able to expand $name variable.

Upvotes: 1

Related Questions