0
bash-3.00# cat > b1.txt
AAA,Apples,123
BBB,Bananas,124
CCC,Carrot,125
bash-3.00# cat > b2.txt
Store1|AAA|123|11
Store2|BBB|124|23
Store3|CCC|125|57
Store4|DDD|126|38
bash-3.00# awk -F"[,|]" 'NR==FNR{a[$1]++;next} !a[$2]' b1.txt b2.txt
Store4|DDD|126|38

When NR==FNR returns true for first file a[$1] gets incremented. next brings back to beginning of the script. But what is !a[$2] doing here? How does it print without even a print command?

  • 1
    I'd advise not running / testing scripts as root unnecessarily. Use a normal user account until you are sure the script is safe enough for root. – jw013 Nov 27 '12 at 17:06
5

From the POSIX awk spec:

An awk program is composed of pairs of the form:

pattern { action }

Either the pattern or the action (including the enclosing brace characters) can be omitted. ... [A] missing action shall be equivalent to:

{ print }

In your case, !a[$2] is the pattern, and the action is missing.

  • hi @jw013,can you add a bit more,, i mean i dont understand how !a[$2] is working to give the output..Thanks – munish Nov 27 '12 at 17:06
  • @munish Then put that in your question. What part of it don't you understand? If you don't understand basic awk, you should go read an awk tutorial. This site is for asking specific questions. – jw013 Nov 27 '12 at 17:08
0

To expand on the previous answer:

awk handles true/false tests numerically; 0 is "false" and any other number is "true". The exclam (!) reverses the test.

So !a[$1] is essentially equivalent to saying, "print if a[$1] is equal to 0".

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.