Michael003 Michael003 - 12 days ago 7
Bash Question

Modify a part of a line on a file

I'm doing a script that should modify the value of a variable on a file which looks like something like that :

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = triton.itinet.fr
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = triton, localhost.localdomain, localhost

relayhost = smtp.free.fr
home_mailbox = Maildir/

virtual_mailbox_domains = $myhostname
virtual_mailbox_base = /var/mail/
virtual_mailbox_maps = hash:/etc/postfix/vmailbox

virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
#virtual_alias_maps = hash:/etc/postfix/virtual


I want to modify the value of relayhost by the user entry, I have done this

modify_relayhost ()
{
read new_relayhost
if (test -e /etc/postfix/main.cf)
then
grep "relayhost" /etc/postfix/main.cf | cut -d= -f1 && echo $new_relayhost
fi
}


But it does not modify the file, it just print me that value called relayhost and write the user's one on the prompt

Answer

You can do this in a single sed command:

read new_relayhost

sed -i.bak -E 's/^([ \t]*relayhost[ \t]*=[ \t]*).*/\1'"$new_relayhost"'/' /etc/postfix/main.cf

This sed command finds relayhost key surrounded by optional spaces and replaces it's value part with value of variable $new_relayhost.