4
2

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 1 year has passed since last update.

ファイルの内容をSQLのin句に当て込むシェル

Last updated at Posted at 2022-10-27

IDかなにかのリストを、下記のようなファイルで持っているとき、これを使ってDBに検索をかけたいときがあります。

$ cat sample.txt
8888-202207010000-3456
7777-202207010000-1234
6666-202207010000-7890
  • 改行コードを','に変換
  • 前後に'をつける
  • select文のin句にあてこむ

とすることで、 select * from table where id in (${ids}) というselect文を作成できます。

$ cat sample.txt | tr  "\n" , | sed -e "s/,/','/g;s/^/'/;s/','$/'/" | awk '{print "select * from user where id in (" $0 ")"}'
select * from user where id in ('8888-202207010000-3456','7777-202207010000-1234','6666-202207010000-7890')
$ ids=$(cat sample.txt | tr  "\n" , | sed -e "s/,/','/g;s/^/'/;s/','$/'/")
$ echo "select * from table where id in ($ids)" 
select * from table where id in ('8888-202207010000-3456','7777-202207010000-1234','6666-202207010000-7890')

ファイルの改行コードがCRLFの場合、trコマンドがCRLFをまとめて変換できないので、CRの削除を先にいれます。

$ ids=$(cat sample.txt | tr -d "\r" | tr  "\n" , | sed -e "s/,/','/g;s/^/'/;s/','$/'/")
4
2
1

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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?