Wednesday, February 15, 2012

Famous Awk One-Liners Explained, Part II: Text Conversion and Substitution, from Peteris Krumins' blog

Hah! Here is where I originally found this, it is pretty crafty:
"43. Remove duplicate, nonconsecutive lines.

awk '!a[$0]++'
This one-liner is very idiomatic. It registers the lines seen in the associative-array "a" (arrays are always associative in Awk) and at the same time tests if it had seen the line before. If it had seen the line before, then a[line] > 0 and !a[line] == 0. Any expression that evaluates to false is a no-op, and any expression that evals to true is equal to "{ print }"."

... and lots of other good stuff too... :-)

No comments:

Post a Comment