-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenamesubs
60 lines (48 loc) · 1.96 KB
/
renamesubs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash
# ------------------- renamesubs -------------------
# A script for renaming subtitles file names to match
# corresponding media files on the same folder,
# matched by season and episode numbers (SXXEXX format).
#
# Usage:
# renamesubs <Directory> <Media Extension> <Subtitles Extension> [Suffix]
#
# Arguments:
# 1. Directory - The directory to search and replace media files and subtitles.
# 2. Media Extension - Media file extension to look for.
# 3. Subtitles Extension - Subtitles file extension to look for.
# 4. Suffix (optional)- An optional suffix to append to renamed subtitles file (before file extension).
# --------------------------------------------------
function pring_usage
{
echo "Usage: $(basename "$0") <Directory> <Media Extension> <Subtitles Extension> [Suffix]"
}
# Assure a valid amount of command-line arguments was passed
if [[ $# -lt 3 ]]; then
echo "Error: Missing parameters." >&2
pring_usage
exit 1
fi
folder_path=${1%/}
media_file_extension="$2"
subtitles_file_extension="$3"
suffix="$4"
# Assure source directory exists and is a directory
if [[ ! -d "$folder_path" ]]; then
echo -e "\"$folder_path\" is an invalid directory."
fi
while IFS= read -r filename;
do
# Assure file extension is valid
if [[ "$filename" != *$media_file_extension ]]; then continue; fi
# Assure file name contains a season and an episode number
episode=$(grep -oP "[Ss]\d{2}[Ee]\d{2}" <<< "$filename")
if [[ -z "$episode" ]]; then continue; fi
subtitles_file=$(find "$folder_path" -name "*$episode*.$subtitles_file_extension" -maxdepth 1)
if [[ -z "$subtitles_file" ]]; then continue; fi
subtitles_extension="${subtitles_file##*.}"
new_file_name="${filename%."$media_file_extension"}$suffix.$subtitles_extension"
if [[ "$subtitles_file" != "$new_file_name" ]]; then
mv "$subtitles_file" "$new_file_name"
fi
done <<< "$(find "$folder_path" -name "*.$media_file_extension" -maxdepth 1)"