diff options
Diffstat (limited to 'ffmgrep.sh')
-rwxr-xr-x | ffmgrep.sh | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/ffmgrep.sh b/ffmgrep.sh new file mode 100755 index 0000000..243c0c7 --- /dev/null +++ b/ffmgrep.sh @@ -0,0 +1,59 @@ +#!/bin/bash + +# LOOKS THROUGH SUBTITLES OF GIVEN FILES TO FIND THE TIMESTAMP(S) OF INPUT STRING + +if (($# < 2)); then + echo >&2 "$0: script requires at least two arguments: Text to grep and at least one file with subtitles, in that order" + exit 1 +else + expr="$1" + shift +fi + +FILES=() +TMPDIR="ffmgrep.XXXXX" +STREAM=0 +CACHEFLAG=0 +COLOR1="\o033[32m" +COLOR2="\o033[36m" +ENDCOLOR="\o033[0m" + +while (($#)); do + if [[ ! -f $1 ]]; then + echo >&2 "$0: $1 is not a valid file" + exit 1 + else + FILES+=("$1") + fi + shift +done + +# we do a little caching + +OLD_TMPDIR=$( ls -ltc /tmp/ | grep -E "^d.*ffmgrep\..{5}" | head -n1 | sed -r "s|.*(ffmgrep)|\/tmp\/\1|g" ) + +if [[ ! -d "$OLD_TMPDIR" ]]; then + TMPDIR=$(mktemp --directory -t "$TMPDIR") +else + for file in "${FILES[@]}"; do + basefile="$(basename "$file")" + if [[ ! -f "${OLD_TMPDIR}/${basefile%.*}.vtt" ]]; then + rm -r $OLD_TMPDIR + TMPDIR=$(mktemp --directory -t "$TMPDIR") + break + fi + done + [[ -d "$OLD_TMPDIR" ]] && TMPDIR="$OLD_TMPDIR" && CACHEFLAG=1 +fi + +for file in "${FILES[@]}"; do + [[ $CACHEFLAG -eq 1 ]] && break + basefile="$(basename "$file")" + [[ -z $(ffmpeg -i "$file" -c copy -map 0:s:0 -frames:s 1 -f null - -v 0 -hide_banner; echo $?) ]] && echo "NO SUBTITLES FOUND IN FILE $file. SKIPPING..." && continue + ffmpeg -i "$file" -map "0:s:${STREAM}" -hide_banner -loglevel error -f webvtt "${TMPDIR}/${basefile%.*}.vtt" +done + +# grep -B 1 --no-group-separator -E -i "$expr" ${TMPDIR}/*vtt | awk 'NR%2{printf "%s ",$0;next;}1' | sed -r "s|${TMPDIR//\//\\\/}\/(.*?)\.vtt-([[:digit:]]+:[[:digit:]]+\.[[:digit:]]+ --> [[:digit:]]+:[[:digit:]]+\.[[:digit:]]+) .*?\.vtt:(.*$)|${COLOR1}\1${ENDCOLOR}: ${COLOR2}(\2)${ENDCOLOR} \3|g" + +grep --with-filename -r "" ${TMPDIR} | sed -r "s|.*\.vtt:$||g" | awk -v RS= '{$1=$1}1' | grep --no-group-separator -E -i "$expr" | sed -r "s|${TMPDIR//\//\\\/}\/[^\/]*\.vtt[-:]||2g; s|${TMPDIR//\//\\\/}\/(.*?)\.vtt[-:](([[:digit:]]+[:\.])+[[:digit:]]+ --> ([[:digit:]]+[:\.])+[[:digit:]]+) (.*$)|${COLOR1}\1${ENDCOLOR}: ${COLOR2}(\2)${ENDCOLOR} \5 |g" + |