Skip to content

Instantly share code, notes, and snippets.

@creaktive
Last active August 29, 2015 14:27
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 creaktive/58d5774ebbe7709d4f43 to your computer and use it in GitHub Desktop.
Save creaktive/58d5774ebbe7709d4f43 to your computer and use it in GitHub Desktop.
convert MySQL dump to CSV
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
my $schema;
my $table;
while (my $line = <>) {
my @csv = ();
if ($line =~ m{^ CREATE \s+ TABLE \s+ `(?<table> \w+)`}ox) {
$table = $+{table};
$schema = [];
} elsif ($schema && $line =~ m{^ \s* `(?<col> \w+)` }ox) {
push @$schema, $+{col};
} elsif ($line =~ m{
(?(DEFINE)
(?<num> -? [0-9]+ (?: \. [0-9]+ )? )
(?<str> '(?: [^'\\] | \\. ) *' )
(?<nul> NULL )
(?<val> (?&num) | (?&str) | (?&nul) )
(?<rec> \( ( (?&val) (?: , (?&val) ) * ) \) (?{ push @csv, $^N }) )
)
^
INSERT \s+ INTO \s+ `(?<table> \w+)` \s+ VALUES \s+
(?&rec) (?: , (?&rec) ) *
; $
}ox) {
my $fh;
my $file = $table . '.csv';
if ($schema) {
open($fh, '>:raw', $file) || die "can't create $file: $!";
say $fh join(',', @$schema);
} else {
open($fh, '>>:raw', $file) || die "can't update $file: $!";
}
$schema = undef;
say $fh $_ for @csv;
close $fh;
} else {
next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment