Chapter Renumber mkv

#!/usr/bin/env bash

# Updates the chapter names in the .mkv metadata so that the chapter name 
# match the actual chapter number. 
#
# During the normal progression of an MKV file, chapters and chapter names
# match up, like so:
#
#   CHAPTER01=00:00:00.000
#   CHAPTER01NAME=Chapter 01
#   CHAPTER02=00:04:37.000
#   CHAPTER02NAME=Chapter 02
#
# However, after two MKVs are joined the original chapter names remain, making
# the chapter names progress like so:
#
#   CHAPTER01=00:00:00.000
#   CHAPTER01NAME=Chapter 01
#   CHAPTER02=00:04:37.000
#   CHAPTER02NAME=Chapter 02
#   CHAPTER03=00:04:37.000
#   CHAPTER03NAME=Chapter 01
#
# This script fixes that issue by editing all the chapter strings to match 
# the chapter number. 

CHAPTERS=`mkvextract chapters -s $1`
NEWCHAPTERS=""

IFS=$'\n'

for X in $CHAPTERS; do 
  # CHAPTER01=*
  if [[ $X =~ ^CHAPTER[[:digit:]]*= ]];then
    NEWCHAPTERS+=$X$'\n'
  # CHAPER01NAME=*
  elif [[ $X =~ ^CHAPTER[[:digit:]]*NAME=.* ]];then
    Y=`echo $X | sed 's/\(^CHAPTER\(.*\)NAME=\).*/\1Chapter \2/'`
    NEWCHAPTERS+=$Y$'\n'
  fi
done

echo "$NEWCHAPTERS" > newchapters

mkvpropedit $1 --chapters newchapters

rm newchapters
Comments