Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Last active October 8, 2015 12:18
Show Gist options
  • Select an option

  • Save bmispelon/3331142 to your computer and use it in GitHub Desktop.

Select an option

Save bmispelon/3331142 to your computer and use it in GitHub Desktop.
Rename subtitles files
function _mvsub_complete()
{
local word=${COMP_WORDS[COMP_CWORD]}
local filename subname
if [[ $COMP_CWORD = 1 ]]; then
# Only allow subtitles files (*.srt)
COMPREPLY=($(compgen -f -X "!*.srt" -- "${word}"))
else
# Only complete non-subtitles files that don't have a matching subtitle
COMPREPLY=()
for item in $(compgen -f -X "*.srt" -- "${word}"); do
filename=$(basename "$item")
subname="${filename%.*}.srt"
if [[ ! -e $subname ]]; then
COMPREPLY+=($item)
fi
done
fi
}
complete -d -F _mvsub_complete mvsub.py
#!/usr/bin/env python3
import argparse
from os import path, rename as os_rename
import shutil
import sys
def mvsub(subtitles, movie):
"""Return a new path for the subtitles file so that its name is the same
as the movie file, with only the file extension differing.
If the given subtitles file has no extension, a ValueError is raised.
"""
_, ext = path.splitext(subtitles)
base, _ = path.splitext(movie)
if not ext:
raise ValueError("The subtitles file has no extension.")
assert movie != base + ext
return base + ext
def prompt_overwrite(subtitles):
msg = "The destination file already exists. Overwrite? (Y/N): "
return input(msg).lower() in {'y', 'yes', '1'}
def get_parser():
parser = argparse.ArgumentParser(description="Move subtitles files.")
parser.add_argument("subtitles", metavar="SUBS",
help="The path to the subtitles file")
parser.add_argument("movie", metavar="MOVIE",
help="The path to the movie file")
parser.add_argument("-c", "--copy", action="store_true",
help="Copy the subtitles file instead of moving it.")
parser.add_argument("-f", "--force", action="store_true",
help="Force the overwriting of the destination file if"
"it already exists.")
return parser
def main(subtitles, movie, copy=False, force=False):
try:
new_subtitles = mvsub(args.subtitles, args.movie)
except ValueError:
return "Invalid subtitles file."
if not force and path.exists(new_subtitles):
if not prompt_overwrite(new_subtitles):
return
if copy:
shutil.copy(args.subtitles, new_subtitles)
else:
os_rename(args.subtitles, new_subtitles)
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
v = main(args.subtitles, args.movie, copy=args.copy, force=args.force)
sys.exit(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment