If pattern match, replace it with #

This command is not working for me.

awk '{if ($1 == server) {$1 = #server} }'  /etc/ntp.conf
# 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


Literal strings must be in "quotes". Also you certainly want to explicitly print.

awk '{if ($1 == "server") {$1 = "#server"} print}'  /etc/ntp.conf

Another solutions

awk '{if ($1 == "server") {print "#"$0} else {print} }'  /etc/ntp.conf
awk '{if ($1 == "server") {printf "#"} print}'  /etc/ntp.conf
1 Like

You forgot these two.. also awk wont save the file permanently.

#server 3.rhel.pool.ntp.org iburst
server ntpserver.com
server  127.127.1.0     # local clock

You forgot to specify WHAT you want exactly.

Howsoever, try

awk '
/^server/       {$1 = "#" $1
                }
/#broadcast /   {print "server ntpserver.com"
                 print "server  127.127.1.0     # local clock"
                 print ""
                }
1
'  /etc/ntp.conf

, save the result to a temp file, and then cp or mv that back to /etc/ntp.conf (as shown umpteen times in these forums).

1 Like

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 
1 Like