3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RDBにLoadするファイルの重複キーをなんとかする

Posted at

キー値の重複検出

RDBにデータをtxtファイルからロードするときにduplicate keyで失敗することが最近多々あるので重複行抽出したり、排除したりを取扱うスクリプトを書いた。

対象

RDBにロードするのに使う、tsvっぽいデータが対象。
一番左の列が主キーで、同じ主キーを持つ行が有ったり無かったりするようなものを想定。

サンプルデータ作成

$ cat > sample.txt
001 duplicate
002 duplicate
003 value
002 duplicate2
001 duplicate
001 duplicate

重複するキー値の抽出

$ awk '{if(a[$1]++==1) print $1}' sample.txt
002
001

重複するキーを持つ2行目以降を排除して抽出

とりあえず、ファイル内でキー重複するのをさけるファイルを作る。

$ awk '{if(!a[$1]++) print}' sample.txt
001 duplicate
002 duplicate
003 value

重複するキーを持つ2行目以降を排除された行を抽出

重複した行を排除された行を出力。

$ awk '{if(a[$1]++) print}' sample.txt
002 duplicate2
001 duplicate
001 duplicate

雑感

sakura editorの正規表現やらexcelでがんばってたけどどう考えてもこの方が早い。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?