1
0

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.

MySQLの検索結果をコマンドラインからsedを用いてCSV変換する

Last updated at Posted at 2023-07-24

備忘録用。

内容

権限の関係上、MySQLコンソールからCSVファイルが出力出来ないので、コマンドラインからCSVファイルを出力する。

xxx@localhost:testDB 11:10:26>select * from test_table into outfile '/home/mitsuaki1229/sample.csv';
ERROR 1045 (28000): Access denied for user 'xxx'@'localhost' (using password: YES)

対応

sedを用いて変換する。

$ mysql -p -uxxx testDB -e "select * from test_table;" | sed -e 's/^/"/g' | sed -e 's/$/"/g' | sed -e 's/\t/","/g' > /home/mitsuaki1229/sample.csv

解説

下記でテーブルからのSELECT情報が取得される。

$ mysql -p -uxxx testDB -e "select * from test_table;"
+-----+-------+
| key | value |
+-----+-------+
| 1   | 12345 |
+-----+-------+

パイプを通った時点で検索結果の枠が消える。

$ mysql -p -uxxx testDB -e "select * from test_table;" | xargs echo
key    value    1    12345

下記で先頭にダブルクオーテーションを付与する。

$ mysql -p -uxxx testDB -e "select * from test_table;" | sed -e 's/^/"/g'
"key    value
"1    12345

下記で末尾にダブルクオーテーションを付与する。

$ mysql -p -uxxx testDB -e "select * from test_table;" | sed -e 's/^/"/g' | sed -e 's/$/"/g'
"key    value"
"1    12345"

下記でタブを変換しつつ、各項目にダブルクオーテーションを付与しつつ、カンマで区切る。

$ mysql -p -uxxx testDB -e "select * from test_table;" | sed -e 's/^/"/g' | sed -e 's/$/"/g' | sed -e 's/\t/","/g'
"key","value"
"1","12345"

※Qiitaに書くとタブがスペースに変換されてますが、タブです。

感想

  • 検索したワンライナーをただコピペして使うのではなく、何をやってるか調べてから使わないと。

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?