Skip to content

Instantly share code, notes, and snippets.

@take-piro
Last active December 23, 2022 15:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save take-piro/dee0ce4180d3138c3cbabab69ca94d78 to your computer and use it in GitHub Desktop.
Save take-piro/dee0ce4180d3138c3cbabab69ca94d78 to your computer and use it in GitHub Desktop.
データベースを丸ごとダンプしたファイルをテーブル毎に分割する方法

CentOS6で確認

// DBダンプ
$ mysqldump -uuser -ppass db_test > dump.sql

// テーブル単位で分割
// ファイル名は table.00 table.01 table.02 ...
$ csplit -f table. dump.sql /^--\ Table\ structure/ {*}

// table.00 にはダンプのコメントだけが書かれているので不要
$ rm table.00

この時点で,table.01 table.02 ...の1行目にはテーブル名があることになる.

-- Table structure for table `sample_table`
--

DROP TABLE IF EXISTS `sample_table`;
...

その1行目にあるテーブル名を抽出してファイル名に置き換えるワンライナースクリプトが以下のとおり.

for FILE in `ls table.*`; do NAME=$(sed -n 1p ${FILE} | sed 's/.*`\(.*\)`/\1/'); mv ${FILE} ${NAME}.sql; done

解説すると,

  1. sed -n 1p ${FILE}
    • ファイルの1行目を出力
    • example: -- Table structure for table `sample_table`
  2. sed 's/.*`(.*)`/\1/'
    • 正規表現でバッククォートで囲まれた部分を抽出
    • example: sample_table
  3. あとはそのテーブル名を使ってファイル名を変更するだけ

--

Macだとcsplitの仕様が異なるため上記の方法ではうまくいかないのでHomebrewを使ってGNU版csplitを入手する.

$ brew install coreutils

coreutilsにはGNU版のコマンドが他にも入っており,コマンドのプレフィックスにgが付いている.
つまり上記のcsplitコマンドは以下のようになる.

$ gcsplit -f table. dump.sql /^--\ Table\ structure/ {*}

--

zshを使っている場合,csplit*でエラーになる.
これはzshのグロッビングによるものである.
簡単な回避策として,コマンドの最初にnoglobコマンドを付ける.

$ noglob csplit -f table. dump.sql /^--\ Table\ structure/ {*}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment