This is an great answer. https://stackoverflow.com/a/6739327/15603477 But Still a little bit confused me.
without a
variable, awk '/^nameserver/ { printf("nameserver 127.0.0.1\n")} {print}' file2
will get:
# Generated by NetworkManager
domain dhcp.example.com
search dhcp.example.com
nameserver 127.0.0.1
nameserver 10.0.0.1
nameserver 127.0.0.1
nameserver 10.0.0.2
nameserver 127.0.0.1
nameserver 10.0.0.3
After try serval combination, I found out that I had to use
awk '/^nameserver/ && !a { printf("nameserver 127.0.0.1\n"); a=1 } {print}' file2
But I am still confused with !a
and a=1
function to stop the printf("nameserver 127.0.0.1\n")
duplication.
printf("nameserver 127.0.0.1\n")
=print "nameserver 127.0.0.1"
. When asking a question it's fine to refer to a previous question/answer but make sure your current question has the sample input, expected output, and code that you're asking about such that it makes sense stand-alone and the people reading it don't need to look up the previous question for context and necessary info.