3

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.

1
  • 1
    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.
    – Ed Morton
    Jan 14 at 13:52
7

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.

6

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.