#!/bin/bash # usage: epub2txtMany *.epub # needs: https://github.com/kevinboone/epub2txt2 , # unzip, zipinfo (for cover extraction) # wishes: catimg (for displaying covers in term) # does: Converts epub to txt and tries to extract cover image # tmp dir cleanup () { [ -n "$tmp" ] && rm -fr "$tmp" } mktmp () { tmp="/tmp/$RANDOM-$$-epub2txtMany" trap cleanup EXIT SIGTERM SIGINT mkdir -m 700 "$tmp" || { echo '!! unable to create a tmp dir' >&2; tmp=; exit 1; } } mktmp # end tmp dir # main while [ $# -gt 0 ]; do file=$(readlink -f "$1") baseext=$(basename "${1}") # file.ext base="${baseext%.*}" # file dir="$(dirname "${file}")" echo "--- $base ---" #set -x # convert to text epub2txt -a -n "$file" > "${dir}/${base}.txt" || exit 1 # extract cover image (chatgpt stuff) unzip -q "$file" -d "$tmp" pushd "$tmp" >/dev/null || exit # Find the content.opf file OPF_FILE=$(find . -name "*.opf" | head -n 1) # Check if the OPF file was found if [ -z "$OPF_FILE" ]; then echo "No content.opf file found." fi # Extract cover image reference COVER_ID=$(grep -i "cover" "$OPF_FILE" | grep -o 'content="[^"]*' | cut -d '"' -f2) COVER_HREF=$(grep -i "$COVER_ID" "$OPF_FILE" | grep -o 'href="[^"]*' | cut -d '"' -f2) # Check if the cover href was found if [ -z "$COVER_HREF" ]; then echo "No cover image reference found in the content.opf file." fi # Find the cover image file COVER_IMAGE=$(dirname "$OPF_FILE")/$COVER_HREF # Check if the cover image file exists if [ ! -f "$COVER_IMAGE" ]; then echo "Cover image file not found." else # Copy the cover image to the current directory cp "$COVER_IMAGE" "${dir}/${base}.jpg" >/dev/null && catimg -H "${dir}/${base}.jpg" fi # clean the tmp dir of everything cleanup && mktmp popd >/dev/null || exit #set +x shift done