PapelPincel
PapelPincel

Reputation: 4393

(sed beginner) replace characters in an env variable

How can I replace caracters "on the fly" when using sed ? Example :

I want this command to be executed : /bin/sed 's/HOSTNAME=.*/HOSTNAME=server_domain_com/g' /etc/sysconfig/network

Instead of this one : /bin/sed 's/HOSTNAME=.*/HOSTNAME=server.domain.com/g' /etc/sysconfig/network

the string "server.domain.com" is contained in a env variable and I would like to replace the dots by an underscore before replacing the appropriate line in /etc/sysconfig/network.

Thank you!

Upvotes: 3

Views: 31587

Answers (2)

lynxlynxlynx
lynxlynxlynx

Reputation: 1433

You can do this with bash substitution too:

/bin/sed -i "s/HOSTNAME=.*/HOSTNAME=${HOSTNAME//./_}/g" /etc/sysconfig/network

The // instructs it to change all occurences (like g in sed). Do not forget the -i flag to actually change the file, not just print it.

Upvotes: 2

Igor Chubin
Igor Chubin

Reputation: 64563

HOSTNAME=$(echo $HOSTNAME | sed s/from/to/g)

Upvotes: 7

Related Questions