SOFTELメモ Developer's blog

会社概要 ブログ 調査依頼 採用情報 ...
てるてる動画

【linux】巨大な圧縮ファイルから必要な部分だけ抜き出す

問題

MySQLのダンプファイルが圧縮されてるんですけど、ここから特定のデータベースの部分だけほしいです。

うまく途中だけ抽出したり、ファイルを分割する方法は?

答え

・使うもの

zegrep, zcat, sed

・手順

MySQLのダンプのDBの区切りは以下のような形式。

-- Current Database: `test`

zegrep で、圧縮したままで行番号を調べる。

$ zegrep -n '^-- Current Database:' mysql_2017-09-28.dmp.gz
19:-- Current Database: `test`
215:-- Current Database: `test2`
...
...

zcat と sed で必要な範囲を切り出す。

$ zcat mysql_2017-09-28.dmp.gz | sed -n -e '19,215p' > test.dmp

複数あれば、複数範囲取得も可能。

$ zcat mysql_2017-09-28.dmp.gz | sed -n -e '123,456p' -e '789,901p' > test.dmp

できたファイルをmysqlへ渡すと、データ投入完了。

$ mysql -u xxx -p データベース名 < test.dmp

わざわざファイルにしないでmysqlコマンドに渡すのも可。

$ zcat mysql_2017-09-28.dmp.gz | sed -n -e '123,456p' -e '789,901p' | mysql -u xxx -p データベース名

メモ1

テーブルの区切りは以下のような形式なので、特定のテーブルを抜き出すことも可能。

-- Table structure for table `aaa`

$ zegrep -n '^-- Table structure' mysql_2017-09-28.dmp.gz
223:-- Table structure for table `wp_commentmeta`
250:-- Table structure for table `wp_comments`
292:-- Table structure for table `wp_links`
327:-- Table structure for table `wp_options`
354:-- Table structure for table `wp_postmeta`
382:-- Table structure for table `wp_posts`
431:-- Table structure for table `wp_term_relationships`
457:-- Table structure for table `wp_term_taxonomy`
487:-- Table structure for table `wp_termmeta`
514:-- Table structure for table `wp_terms`
542:-- Table structure for table `wp_usermeta`
570:-- Table structure for table `wp_users`
...
...

↓ wp_posts だけ取得

$ zcat mysql_2017-09-28.dmp.gz | sed -n -e '382,431p' > wp_posts.dmp

「最終行まで」は sed -n -e ‘1234,$p’ のように、$を使います。

メモ2

いったん展開するのもありです → https://www.softel.co.jp/blogs/tech/archives/4894

関連するメモ

コメント