Bash-script. Shift seconds

bashdateshell-scripttext processing

In bash I don't know how to do that. I need to do a bash-script. At stdin I have .srt file of subtitles in this format:

num
HH:MM:SS,SSS --> HH:MM:SS,SSS
text line 1
text line 2
...

HH:MM:SS,SSS start and finish of title for text.

Script must shift seconds. (it can be + or -)

Example:

$cat bmt.srt
5
00:01:02,323 --> 00:01:05,572
Hello, my frieds!
6
....

$./shifter.sh +3<mbt.srt
5
00:01:05,323 --> 00:01:08,572
Hello, my frieds!
6

I need to grab all HH:MM:SS and convert them to seconds firstly. Is somebody able do this without sed?

Best Answer

Unless the subtitle file spans more than 24 hours, you can use date for this:

#!/usr/bin/env bash

set -o errexit -o noclobber -o nounset -o pipefail

date_offset="$1"

shift_date() {
    date --date="$1 $date_offset" +%T,%N | cut -c 1-12
}

while read -r line
do
    if [[ $line =~ ^[0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]\ --\>\ [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9][0-9][0-9]$ ]]
    then
        read -r start_date separator end_date <<<"$line"
        new_start_date="$(shift_date "$start_date")"
        new_end_date="$(shift_date "$end_date")"
        printf "%s %s %s\n" "$new_start_date" "$separator" "$new_end_date"
        echo "New date"
    else
        printf "%s\n" "$line"
    fi
done

For some reason you need to use decimal numbers with this, but it works:

$ ./shifter.sh "+3.0 seconds" < bmt.srt
5
00:01:05,323 --> 00:01:08,572
New date
Hello, my frieds!
6
Related Question