1

I wanted to remove duplicate lines from a file based on a column. A quick search let me this page which had the following solution:

awk '!x[$1]++' filename

It works, but I am not sure how it works. I know it uses associate arrays in awk but I am not able to infer anything beyond it.

Update:

Thanks everyone for the explanation. With my new knowledge, I have wrote a blog post with further explanation of how it works.

4

1 に答える 1

3

その awk スクリプト!x[$1]++は、という名前の配列を埋めxます。テキスト行の最初の単語 ($1テキスト行の最初の単語を指す) が であるとしますline1。これにより、アレイに対して次の操作が効果的に行われます。

x["line1"]++

配列の「インデックス」(キー) はファイル内で検出されたテキスト (line1この例では) であり、そのキーに関連付けられた値は 1 ずつ増加する整数です。

テキストの一意の行が検出されると、配列の現在の値はゼロであり、その後 1 にインクリメントされます。not演算子!は、テキストの新しい一意の行ごとに非ゼロ (true) と評価し、それを出力します。次に同じ値が検出されたとき、配列内の値はゼロ以外であるため、not操作の結果はゼロ (false) になり、その行は出力されません。

同じことを「賢くない」書き方 (ただし、より明確で楽しくない可能性があります) は、次のようになります。

{
if (x[$1] == 0 ) 
   print
x[$1]++
}
于 2013-03-14T19:42:57.403 に答える