This seems to do the job:
Code:
#!/bin/bash
mkdir -p chapters
sed '/<h2/s/^/<\/body>\n<\/html>\n/' $1| sed -n '1,/<body/{1h;1!H};/<h2/{x;p;x};p' | csplit -f "chapters/" -b "%2.2d.xhtml" - "/<\/html>/+1" "{$(( $(grep -c '<h2' $1) - 1 ))}"
cd chapters
for f in ??.xhtml
do for t in $(grep -ho "href=.#[^\"']\+" $f|cut -c8-180)
do sed -i "s/\([\"']\)#${t}['\"]/\1$(grep -l "\(name\|id\)=['\"]${t}['\"]" ??.xhtml|grep -v "${f}")#${t}\1/" $f
done
done