Skip to content

Instantly share code, notes, and snippets.

@madssj
Created June 4, 2013 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save madssj/5704571 to your computer and use it in GitHub Desktop.
Save madssj/5704571 to your computer and use it in GitHub Desktop.
#!/bin/sh
if [ $# -ne 2 ]
then
echo "Usage: $0 <postgresql sql dump> <db_name>" >&2
exit 1
fi
db_file=$1
db_name=$2
if [ ! -f $db_file -o ! -r $db_file ]
then
echo "error: $db_file not found or not readable" >&2
exit 2
fi
grep -b "^\connect" $db_file | grep -m 1 -A 1 "$db_name$" | while read line
do
bytes=`echo $line | cut -d: -f1`
if [ -z "$start_point" ]
then
start_point=$bytes
else
end_point=$bytes
fi
done
if [ -z "$start_point" -o -z "$end_point" ]
then
echo "error: start or end not found" >&2
exit 3
fi
db_length=`expr $end_point - $start_point`
tail -c +$start_point $db_file | head -c $db_length | tail +3
@Coolknight
Copy link

In my case, outside of the while loop, start_point and end_point where always unset. I had to change some things in order to get it work. Also, the tail +3 and this grep didn't work for me either so i changed it a bit. Here is the same script with a few modifications. Thank you very much for your work madssj.

#!/bin/bash

START=0
END=0

if [ $# -ne 2 ]
then
    echo "Usage: $0 <postgresql sql dump> <db_name>" >&2
        exit 1
fi

DB_FILE=$1
DB_NAME=$2

if [ ! -f $DB_FILE -o ! -r $DB_FILE ]
then
        echo "error: $DB_FILE not found or not readable" >&2
        exit 2
fi

while read LINE
do
        LINE_NUMBER=`echo $LINE | cut -d: -f1`

        if [ $START -eq 0 ]
        then
                START=$(($LINE_NUMBER+1))
        else
                END=$(($LINE_NUMBER+1))
        fi
done < <(egrep -n "\\connect\ |PostgreSQL\ database\ dump\ complete" $DB_FILE | grep -m 1 -A 1 "$DB_NAME")

if [ $START -eq 0 -o $END -eq 0 ]
then
        echo "error: start or end not found" >&2
        exit 3
fi

DB_LENGTH=`expr $END - $START`

head -$END $DB_FILE | tail -$DB_LENGTH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment