View Single Post
Old 10-10-2014, 09:22 PM   #10
baochan
Enthusiast
baochan doesn't litterbaochan doesn't litter
 
baochan's Avatar
 
Posts: 30
Karma: 100
Join Date: Mar 2013
Location: USA
Device: Kobo Aura H2O, Pyrus Mini
Partly as a learning exercise, I made a Bash shell script to automatically change the files so they sort correctly on Kobo devices. I'll post it here in case any other Linux users might find it helpful. It renames the files in the CBZ or CBR files by padding all one- or two-digit numbers with leading zeros, and appending the directory/chapter name to the beginning of any files that are in subdirectories. The zero-padding and directory-appending code can be pulled off into their own scripts as well, they should work stand-alone as written.

It should work on any system with Bash, including Cygwin I think, as long as it has rar, zip, and perl (needed for the regex I used - if anyone can figure out a way to do it with sed let me know). It also accepts spaces or apostrophes in filenames, but check the new files to make sure they're about the same size as the old ones.

Code:
#!/bin/bash
# kobocomic: Modifies CBR and CBZ files to be displayed correctly on Kobo devices
# Requires perl, rar, unrar, zip, unzip

if [ "$#" -lt 1 ]; then
  echo Supply a CBZ, CBR, ZIP, or RAR file to modify. 
  exit
fi

if [ -d "tmp_kobocomic" ]; then
  echo Directory tmp_kobocomic exists
  exit
fi

for z in "$@"
do
  mkdir tmp_kobocomic
  if [ ${z: -4} == ".cbz" ] || [ ${z: -4} == ".zip" ]; then
    filetype="zip"
  elif [ ${z: -4} == ".cbr" ] || [ ${z: -4} == ".rar" ]; then
    filetype="rar"
  else
    continue
  fi

  if [ $filetype == "rar" ]; then
    echo Unraring: $z
    unrar x "$z" tmp_kobocomic >/dev/null
  else
    echo Unzipping: $z
    unzip -d tmp_kobocomic "$z" >/dev/null
  fi

  cd tmp_kobocomic

  # Add leading zeros to any single or double digits in files, recursively
  # perl is needed for lookahead/behind
  echo \ \ Padding numbers with leading zeros
  find . -depth | while read i; do
    mv -n "$i" "$(dirname "$i")/$(basename "$i" | perl -ne 's/(?<!\d)(\d)(?!\d)/0$1/g; s/(?<!\d)(\d\d)(?!\d)/0$1/g; print;')" 2>/dev/null
  done

  # Append directory name to all files in subdirectories
  echo \ \ Appending directory name to all files
  find . -mindepth 2 -type f | while read i; do
    dir=$(dirname "$i")
    mv "$i" "$dir/$(basename "$dir")_$(basename "$i")"
  done

  if [ $filetype == "rar" ]; then
    echo \ \ Compressing: ${z:0:-4}_new.cbr
    rar a "${z:0:-4}_new.cbr" * >/dev/null
    mv "${z:0:-4}_new.cbr" ..
  else
    echo \ \ Compressing: ${z:0:-4}_new.cbz
    zip -r "${z:0:-4}_new.cbz" * >/dev/null
    mv "${z:0:-4}_new.cbz" ..
  fi

  cd ..
  rm -r tmp_kobocomic
  
done
baochan is offline   Reply With Quote