1

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?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
AmigoSe
  • 366
  • 1
  • 2
  • 13

1 Answers1

1

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.

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236
  • sed operates on regexps, not strings, so you need to escape any RE metacharacters in the search field of your command. In this specific case that's just the `.`s but see http://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed/29626460#29626460 for how to deal with that in general. – Ed Morton Jun 05 '16 at 14:06