Home > Back-end >  sql dump automatic change
sql dump automatic change

Time:01-30

I'm looking to automatically change an sql dump (without needing to know the original db name) - so if the SQL Dump says for example...

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `mysql` /*!40100 DEFAULT CHARACTER SET latin1 */;

I want it to automatically scan for all CREATE DATABASE lines in the file and append mysql to show as prefix_mysql

For all CREATE DATABASE records in the file - is that possible? - I can find the database names here, but I don't know how to tie it together

find . -name \*.sql -type f -exec bash -c '
echo "found $# sql dumps"
for file; do
dbnames=( $(grep -Poe "CREATE DATABASE [^\`]*\`\K[^\`]*" "$file") )

printf "\n          file: %s\n" "$file"
printf "%2s database(s): %s\n" "${#dbnames[*]}" "${dbnames[*]}"

done
> ' 'find-sh' {}  

Also tried

read -p "enter the cPanel username: " cpuser
cd "/home/$cpuser/public_html"
dbnames=($(grep $sqldump -Poe "CREATE DATABASE [^\`]*\`\K[^\`]*"))
for i in ${dbnames[@]}; do sed -i "s/$i/$cpuser_$i" $sqldump; done

However I get;

sed: -e expression #1, char 11: unterminated `s' command
sed: -e expression #1, char 13: unterminated `s' command
sed: -e expression #1, char 13: unterminated `s' command

CodePudding user response:

Let sed search for the pattern itself when substituting, rather than using grep to find it.

find . -name '*.sql' -exec sed -i "s/\\(CREATE DATABASE [^\`]*\`\\)/\\1${cpuser}_/" {}  

Your code doesn't only replace in the CREATE DATABASE line, it replaces all occurrences of the database name. Which means if the database name appears in column names, dumped values, etc. these will get the prefix added.

Also, you need to use ${cpuser} with braces if you want to put a literal _ after it. Otherwise it looks for a variable named cpuser_.

  • Related