Extract Lines Between Two Patterns From A File

Yesterday, I was trying to restore one of my old blog sites that was written in Chinese, so that I can continue blogging. I had MySQL database backed up in a dumped SQL file, however, I noticed that I dumped all databases into one file, which stopped me from loading the full dump file into MySQL as there are other databases that I can’t just load them in, like “mysql” system database.

So my goal is simple, to extract this particular database out from the dump file.

Method 1:

Examining the dump file, I can see that they can be separated by the following lines:

-- Current Database: `db1`
-- Current Database: `db2`
-- Current Database: `db3`
-- Current Database: `db4`
-- Current Database: `db5`
-- Current Database: `db6`
....

Thanks to this thread on StackOverflow, the solution is simple, just run below command to extract all lines between “Current Database: `db4`” and “Current Database: `db5`“:

sed '/Current Database: `db4`/,/Current Database: `db5`/!d' dump.sql > db4.sql

What above command does is to search for lines “Current Database: `db4`” and “Current Database: `db5`“, and delete everything that is NOT between those two lines (!d means not matching then delete, “,” means between the lines).

Method 2

Firstly grep the pattern and print out the line numbers:

ubuntu@localhost:~/chenhui$ grep -n 'Current Database' dump.sql
19: -- Current Database: `db1`
382: -- Current Database: `db2`
744: -- Current Database: `db3`
1137: -- Current Database: `db4`
3401: -- Current Database: `db5`
5604: -- Current Database: `db6`
....

Then, use those line number to capture all lines in between:

sed -n 1137,3401p dump.sql > db4.sql

More information can be found from this blog post.

Hope above helps!!