Mysql – Extracting a line section of thesql backup using sed

awkgrepMySQLsed

I occasionally need to extract a single record from a mysqlbackup

To do this, I first extract the single table I want from the backup…

sed -n -e '/CREATE TABLE.*usertext/,/CREATE TABLE/p' 20120930_backup.sql > table.sql

In table.sql, the records are batched using extended inserts (with maybe 100 records per insert before it creates a new line starting with INSERT INTO), so they look like…

INSERT INTO usertext VALUES (1, field2 etc), (2, field2 etc),

INSERT INTO usertext VALUES (101, field2 etc), (102, field2 etc), ...

Im trying to extract record 239560 from this, using…

sed -n -e '/(239560.*/,/)/p' table.sql > record.sql

Ie.. start streaming when it finds 239560, and stop when it hits the closing bracket

But this isnt working as I hoped, it just results in the full insert batch being output.

Please can someone give me some pointers as to where Im going wrong?

Would I be better off using awk for extracting segments of lines, and use sed for extracting lines within a file?

Best Answer

Based on Iain's answer I've come up with this sed trick...

$ sed  's/\(INSERT[^(]*\).*\((239560,[^)]*)\),.*/\1\2/' sample.sql | tee 1-record.sql
INSERT INTO usertext VALUES (239560, 2, 3, 4)
$ 

-- Variation without using sed... You can extract values of some row/insert that match just that one number.

$ cat sample.sql
INSERT INTO usertext VALUES (101, field2 etc), (102, field2 etc), (239560, 2, 3, 4), (5, 8, 9)
INSERT INTO usertext VALUES (101, field2 etc), (102, field2 etc), (1239560, 2, 3, 4), (5, 8, 9)
$ egrep -o '(\(239560\,[^)]+\))' sample.sql        
(239560, 2, 3, 4)
$ 

rest of insert can be scripted easily if you use -n switch with grep to catch line of match and then just cut everything up to first (

Related Topic