Skip to content

Instantly share code, notes, and snippets.

@neilalbrock
Created April 1, 2012 19:39
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save neilalbrock/2278039 to your computer and use it in GitHub Desktop.
Save neilalbrock/2278039 to your computer and use it in GitHub Desktop.
Split MySQL dump into a file per database
#!/usr/bin/perl -w
#
# splitmysqldump - split mysqldump file into per-database dump files.
use strict;
use warnings;
my $dbfile;
my $dbname = q{};
my $header = q{};
while (<>) {
# Beginning of a new database section:
# close currently open file and start a new one
if (m/-- Current Database\: \`([-\w]+)\`/) {
if (defined $dbfile && tell $dbfile != -1) {
close $dbfile or die "Could not close file!"
}
$dbname = $1;
open $dbfile, ">>", "$1_dump.sql" or die "Could not create file!";
print $dbfile $header;
print "Writing file $1_dump.sql ...\n";
}
if (defined
$dbfile && tell $dbfile != -1) {
print $dbfile $_;
}
# Catch dump file header in the beginning
# to be printed to each separate dump file.
if (!
$dbname) { $header .= $_; }
}
close $dbfile or die "Could not close file!"
@jesseleite
Copy link

Ahh, this saved me a ton of time, thank you!

@andriesfilmer
Copy link

Whow, thanks.

@andriesfilmer
Copy link

My 50cents, have made the regex a bit more strict with ^$.

(m/^-- Current Database\: \`([-\w]+)\`$/)

Thanks again.

@batura-endika
Copy link

Works really fine!

@zlove
Copy link

zlove commented May 13, 2016

Worked like a charm on a 1GB mysql dump with about 80 dbs. Thanks!

@agvozden
Copy link

Can't use an undefined value as a symbol reference at bin/splitmysqldump.pl line 34, <> line 4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment