shellスクリプト--awk配列による重複行の除去

1504 ワード

重複行を削除する方法はいろいろありますが、ここでは3つ紹介します.
テストテキスト:
[root@172-0-10-222 myscripts]# cat testfile
andy 123456
hanna 123456
hello world
welcome fuck
andy 123456
hello world
andy andy

   , andy 123456 hello world    。

(1)sort,uniqコマンドによる重複行の除去
[root@172-0-10-222 myscripts]# cat testfile | sort | uniq
andy 123456
andy andy
hanna 123456
hello world
welcome fuck

ここでは、各ローをデフォルトのルールでソートし、重複するローを削除します.
(2)awk配列による重複行の除去
[root@172-0-10-222 myscripts]# cat testfile | awk '!arr[$0]++{print $0}'
andy 123456
hanna 123456
hello world
welcome fuck
andy andy

       cat testfile | awk '!arr[$0]++'

分析:各行のデータを配列の下付き記号として、ある下付き記号xが初めて現れたときarr[x]は0、2回目、3回目、...n回目に現れたときarr[x]は0ではなかった.ここ、!arr[$0]++は、最初に現れた行を選択して印刷出力する.
(3)awk配列による繰返し行の詳細表記の除去
[root@172-0-10-222 myscripts]# cat testfile | awk '{arr[$0]=1}END{for(i in arr){print i}}'
welcome fuck
hanna 123456
andy 123456
hello world
andy andy

分析:各行を配列下として配列に値を付与し、行下を繰り返すと前の下を置換します.残りの下付き文字を出力すればいいです.
 
ケース:重複番号行の削除
番号ファイル
[root@172-0-10-222 myscripts]# cat testfile
andy 15871731153
hanna 15387876543
hello 15578765389
welcome 15871731153
andy 13987273647
hello 15871731153
andy 15871731153

ファイル内の番号が重複する行を削除
[root@172-0-10-222 myscripts]# cat testfile | awk '!arr[$2]++'
andy 15871731153
hanna 15387876543
hello 15578765389
andy 13987273647