14

I learned a really handy way to remove duplicate lines retaining the order from Remove duplicates without sorting file - BASH.

Say, if you have the following file,

$cat file
a
a
b
b
a
c

you can use the following to remove the duplicate lines:

$awk '!x[$1]++' file
a
b
c

How does this work in terms of precedence of operations?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alby
  • 5,522
  • 7
  • 41
  • 51
  • I don't understand the question? It removes duplicate lines. What precedence do you mean? – Oliver May 31 '12 at 22:36
  • 6
    Just a note: it will remove not only the duplicated lines but _all lines with the same value at the first column_, too! Add a line with `d a` and `d b` to the file and you will see what I mean. To remove only duplicated lines, you can write `!x[$0]++`, since `$0` returns all the line, not only the first column. To understand it better, see @larsmans answer. – brandizzi May 31 '12 at 22:40
  • @Oliver: Operator precedence. – Dennis Williamson Jun 01 '12 at 00:08
  • @brandizzi sorry for the delay! I usually wait 3~5days to select the best answer – Alby Jun 04 '12 at 18:48

2 Answers2

22

The expression is parsed as

!(x[$(1)]++)

So, from the inside out, it's:

  • Take field 1 of the current input line, $(1) (note that $ is an operator in AWK, unlike in Perl).
  • Index x with the value of field 1; if x is an unbound variable, bind it to a new associative array.
  • Post-increment x[$(1)]; a rule similar to the one in C applies, so the value of the expression is that of x[$(1)] prior to the increment, which will be zero if x[$(1)] has not yet been assigned a value.
  • Negate the value of the previous, which will yield truth when x[$(1)] is zero.
  • Actually do the increment so that x[$(1)] gets a non-zero value. So, the next time, x[$(1)] for the same value of $(1) will return 1.

This expression is then evaluated for every line in the input and determines whether the implied default action of awk should be executed, which is to echo the line to stdout.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 11
    Just a complement: `!x[$1]++` is an expression which, if true, will execute the following block of code. However, it does not have any block of code; in this case, the default behavior is to execute the `print` command, which prints the current line if no parameter is given to it. This means that, in this case, `!x[$1]++` is equivalent to `!x[$1]++{print;}`. So, the first line a value is returned by `$(1)`, the result of `!x[$1]++` will be true and the line will be printed out; the next times, however, `!x[$1]++` will yield false, and the lines will not be printed. – brandizzi May 31 '12 at 22:47
0

In AWK arrays are associative, so the first column or first field of each line, $1, is used as an index for the array x.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131