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\n")} {print}' file2 will get:

# Generated by NetworkManager
domain dhcp.example.com
search dhcp.example.com

After try serval combination, I found out that I had to use awk '/^nameserver/ && !a { printf("nameserver\n"); a=1 } {print}' file2

But I am still confused with !a and a=1 function to stop the printf("nameserver\n") duplication.

  • 1
    printf("nameserver\n") = print "nameserver". 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.
    – Ed Morton
    Jan 14 at 13:52

2 Answers 2


Name the variable already_inserted instead of a and it will become clear. Then it reads like:

if my_pattern matches and not already_inserted { insert "some text"; already_inserted=true; }

awk will run this command for each line.


the use of these kind of variables known as "flag variable", that let the program knows a certain condition has met then decide based on its value for further processing; here that's a simple control flag that whenever it doesn't set and has 0 or empty value (in awk default variables' value is 0 when doing integer comparison or its empty string when doing string comparison) then the string will be printed and the flag a=1 will be set, and so it will stop adding duplicates since that's now non-zero value.

In many programming languages, ! (not) negates the evaluation result of an statement which when it's used like ! a, it negates the evaluation result of the a variable, if a=0, then ! a will retun 1, or will retun 0 if it was a=1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.