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