AmigoSe
AmigoSe

Reputation: 366

Search and replace inside of square brackets

I've gone over many threads and tried different settings to perform search and replace using Sed and AWK, however, I was not that successful.

I need to replace #relayhost = [mailserver.isp.tld] with relayhost = [smtp.mydomain.com].

I used below two commands but both really do not provide required result.

sed -i 's/#relayhost = [mailserver.isp.tld]/relayhost = [smtp.mydomain.com]/g' /etc/postfix/main.cf. 

Also tried

sed -e '0,/#relayhost = [mailserver.isp.tld]/{//i\[smtp.mydomain.com]' -e '}' /etc/postfix/main.cf

I need to uncomment the line and change the content side the square brackets. Any suggestions why it's not working?

Upvotes: 1

Views: 145

Answers (1)

janos
janos

Reputation: 124824

You need to escape the [] in the pattern, as well as other characters that have special meaning in regular expressions, in this example the .:

sed -i 's/#relayhost = \[mailserver\.isp\.tld\]/relayhost = [smtp.mydomain.com]/' /etc/postfix/main.cf. 

As a side note, I dropped the /g flag, you don't need it.

See also this related answer for dealing with escaping metacharacters in patterns.

Upvotes: 1

Related Questions