Split or Restore only Part of a Complete MySQLdump
If you keep your database backed up into a single SQL dump and want to retrieve only the part matching one database, perhaps to transfer to another system, I find the simplest and most re-usable trick is to use sed
's "p" function which prints the "pattern space" to STDOUT
even when normal output is suppressed:
sed -n '/^-- Current Database: `YOURDBNAME`/,/^-- Current Database: `/p' alldbs.sql > out.sql
In the above command the -n
will suppress all the normal output from sed
-- otherwise we'd simply list every line of the input file. Then we list two regular expressions, comma separated (the "p" function accepts a maximum on 2 patterns). This tells the "p" function to start printing when it sees the first expression, in this case the line signifying that the start of the desired database's backup, and stops when it sees the second -- the header to the next backed up database (inclusive). sed
is pointed to our database backup and we redirect any STDOUT
output to a new file.
From there you just have to send the identified SQL commands to mysql
:
mysql -u root -p YOURDBNAME < out.sql
You can re-use this sed
trick on other files when you know where the interesting part starts and ends.