|
| 1 | +#!/bin/bash |
| 2 | +# |
| 3 | +# Extract WordPress tables from a one-database dump. |
| 4 | +# Usage: mysql-grep-table.sh "db-dump.sql" [<DB_PREFIX>] > "only-wp-tables.sql" |
| 5 | +# |
| 6 | +# VERSION :0.1 |
| 7 | +# DATE :2014-10-26 |
| 8 | +# AUTHOR :Viktor Szépe <viktor@szepe.net> |
| 9 | +# LICENSE :The MIT License (MIT) |
| 10 | +# URL :https://github.com/szepeviktor/debian-server-tools |
| 11 | +# BASH-VERSION :4.2+ |
| 12 | + |
| 13 | + |
| 14 | +#FIXME: handle top and bottom comment blocks /*!40101 SET */" |
| 15 | +# sed -n '/^\/\*![0-9]\{5\} SET /p' |
| 16 | + |
| 17 | + |
| 18 | +# Find a section delimited by "--" |
| 19 | +Grep_mysql_section() { |
| 20 | + local SECTION="$1" |
| 21 | + |
| 22 | + sed -n '/^-- '"$SECTION"'$/{N; :a;N; /\n--\($\| Dump completed\)/{p;d}; ba}' |
| 23 | +} |
| 24 | + |
| 25 | +# Find all four sections |
| 26 | +Dump_table() { |
| 27 | + local FILE="$1" |
| 28 | + local TABLE="$2" |
| 29 | + |
| 30 | + Grep_mysql_section "Table structure for table \`${TABLE}\`" < "$FILE" |
| 31 | + Grep_mysql_section "Dumping data for table \`${TABLE}\`" < "$FILE" |
| 32 | + Grep_mysql_section "Indexes for table \`${TABLE}\`" < "$FILE" |
| 33 | + Grep_mysql_section "AUTO_INCREMENT for table \`${TABLE}\`" < "$FILE" |
| 34 | +} |
| 35 | + |
| 36 | +# Find table data in WP DB Migrate output |
| 37 | +Wpdbmigrate_table() { |
| 38 | + local FILE="$1" |
| 39 | + local TABLE="$2" |
| 40 | + |
| 41 | + sed -n '/^# Table: `'"$TABLE"'`$/{:a;N; /\n# End of data contents of table `'"$TABLE"'`$/{N;p;d}; ba}' < "$FILE" |
| 42 | +} |
| 43 | + |
| 44 | +# Detect dump type |
| 45 | +Grep_table() { |
| 46 | + local FILE="$1" |
| 47 | + local TABLE="$2" |
| 48 | + local FIRST_LINE |
| 49 | + |
| 50 | + FIRST_LINE="$(head -n 1 "$FILE")" |
| 51 | + |
| 52 | + # mysqldump |
| 53 | + # phpMyAdmin |
| 54 | + if grep -q -- "^-- MySQL dump" <<< "$FIRST_LINE" \ |
| 55 | + || grep -q -- "^-- phpMyAdmin SQL Dump" <<< "$FIRST_LINE"; then |
| 56 | + Dump_table "$FILE" "$TABLE" |
| 57 | + |
| 58 | + # WP DB Migrate plugin |
| 59 | + elif grep -q -- "^# WordPress MySQL database migration" <<< "$FIRST_LINE"; then |
| 60 | + Wpdbmigrate_table "$FILE" "$TABLE" |
| 61 | + |
| 62 | + # unknown |
| 63 | + else |
| 64 | + echo "Unknown dump type." >&2 |
| 65 | + exit 2 |
| 66 | + fi |
| 67 | +} |
| 68 | + |
| 69 | +############## |
| 70 | + |
| 71 | +DB_DUMP="$1" |
| 72 | +if ! [ -f "$DB_DUMP" ]; then |
| 73 | + echo "Dump file does not exist." >&2 |
| 74 | + exit 1 |
| 75 | +fi |
| 76 | + |
| 77 | +DB_PREFIX="wp_" |
| 78 | +[ -z "$2" ] || DB_PREFIX="$2" |
| 79 | + |
| 80 | +#TODO: multisite tables |
| 81 | +for T in commentmeta comments links options postmeta posts \ |
| 82 | + terms term_relationships term_taxonomy usermeta users; do |
| 83 | + |
| 84 | + Grep_table "$DB_DUMP" "${DB_PREFIX}${T}" |
| 85 | +done |
0 commit comments