# grep server /etc/ntp.conf
# Use public servers from the pool.ntp.org project.
server 0.rhel.pool.ntp.org iburst
server 1.rhel.pool.ntp.org iburst
server 2.rhel.pool.ntp.org iburst
server 3.rhel.pool.ntp.org iburst
#broadcast 192.161.255 autokey # broadcast server
Output:
# grep server /etc/ntp.conf
# Use public servers from the pool.ntp.org project.
#server 0.rhel.pool.ntp.org iburst
#server 1.rhel.pool.ntp.org iburst
#server 2.rhel.pool.ntp.org iburst
#server 3.rhel.pool.ntp.org iburst
server ntpserver.com
server 127.127.1.0 # local clock
#broadcast 192.161.255 autokey # broadcast server
The following uses a stage variable met that controls where to insert the new text. If there was no match encountered (met==0) or the new text was not yet inserted (met==1), it inserts the new text at the END. Therefore the new text insertion is put into a function printnew().
awk '
function printnew() {
print "server ntpserver.com"
print "server 127.127.1.0 # local clock"
}
{
if ($1 == "server") {
print "#"$0
if (met==0) met=1
} else {
print
if (met==1) {
print
printnew()
met=2
}
}
}
END {
if (met<2) printnew()
}
' /etc/ntp.conf