Skip to content

Instantly share code, notes, and snippets.

@Mrjavaci
Forked from thanuja919/split-mysql-dump.sh
Created April 22, 2023 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mrjavaci/89a5b84be29237194e226cb4ae034371 to your computer and use it in GitHub Desktop.
Save Mrjavaci/89a5b84be29237194e226cb4ae034371 to your computer and use it in GitHub Desktop.
split-mysql-dump
#!/usr/bin/env bash
#When executing the script keep the main db dump in another folder.
AWK=awk
REGEX_NAME="Current Database: \`(.*)\`"
# Checks argument and prints usage if needed
if [ "$#" -lt "1" ]
then
echo "Usage: $0 <dump.sql>"
exit 1
fi
# Splits dump into temporary files
$AWK '/Current Database\: .*/{g++} { print $0 > g".tmpsql" }' $1
# Renames files or appends to existing one (to handle views)
for f in *.tmpsql
do
DATABASE_LINE=`head -n1 $f`
[[ $DATABASE_LINE =~ $REGEX_NAME ]]
TARGET_FILE="${BASH_REMATCH[1]}.sql"
if [ -f $TARGET_FILE ]; then
cat $f >> $TARGET_FILE
rm $f
else
mv $f ${BASH_REMATCH[1]}.sql
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment