Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #!/bin/bash
  2. # extract all postgres databases from a sql file created by pg_dumpall
  3. # this script outputs one .sql file for each database in the original .sql file
  4. # unless you pass the name of a database in the dump
  5.  
  6. if [ $# -lt 1 ]
  7. then
  8. echo "Usage: $0 <postgresql sql dump> [dbname]" >&2
  9. exit 1
  10. fi
  11.  
  12. DB_FILE=$1
  13. DB_NAME=$2
  14.  
  15. if [ ! -f $DB_FILE -o ! -r $DB_FILE ]
  16. then
  17. echo "error: $DB_FILE not found or not readable" >&2
  18. exit 2
  19. fi
  20.  
  21. # this loops through all instances of "\connect databasename"
  22. # and tells the line number. the $LINE variable will look like this:
  23. # 3504:\connect databasename
  24. egrep -n "\\\\connect\ $DB_NAME" $DB_FILE | while read LINE
  25. do
  26. # get "databasename" from "3504:\connect databasename"
  27. DB_NAME=$(echo $LINE | awk '{print $2}')
  28.  
  29. echo "Evaluating $DB_NAME..."
  30.  
  31. # get "3504" from contains "3504:\connect databasename"
  32. STARTING_LINE_NUMBER=$(echo $LINE | cut -d: -f1)
  33.  
  34. # the exported sql should not contain the first line that reads
  35. # "\connect databasename" otherwise you won't be able to rename the database
  36. # if we start after that line, you could do something like this:
  37. # psql new_databasename < databasename.sql
  38. STARTING_LINE_NUMBER=$(($STARTING_LINE_NUMBER+1))
  39.  
  40. # use tail to print out all of the file after the STARTING_LINE_NUMBER
  41. TOTAL_LINES=$(tail -n +$STARTING_LINE_NUMBER $DB_FILE | \
  42. # search for the line at the end of the sql import for this database
  43. egrep -n -m 1 "PostgreSQL\ database\ dump\ complete" | \
  44. # make sure we only act on the first match
  45. head -n 1 | \
  46. # and get the line number where we found the match
  47. cut -d: -f1)
  48. # we should now know how long the sql import is for this database
  49. # specifically, we should know how many lines there are
  50.  
  51. echo "$DB_NAME begins on line $STARTING_LINE_NUMBER and ends after $TOTAL_LINES lines"
  52.  
  53. # use tail to pipe from the starting line number, and piping X amount of lines (where X is TOTAL_LINES)
  54. # this gets piped into a file named after the database: DB_NAME.sql
  55. tail -n +$STARTING_LINE_NUMBER $DB_FILE | head -n +$TOTAL_LINES > $DB_NAME.sql
  56.  
  57. done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement