Last active
June 4, 2024 21:47
-
-
Save andre3k1/301cbb8822e3fe69d73d5985550b113e to your computer and use it in GitHub Desktop.
Converts SRT (.srt) subtitle files in a folder to UTF-8 encoding using iconv
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
# Function to print usage | |
function usage() { | |
echo "Usage: $0 <folder_path>" | |
echo "e.g. $0 /Movies/MyMovie/Subtitles" | |
echo "Please provide a folder path as the single argument to this script." | |
echo "All files in the selected folder will be converted to UTF-8 encoding." | |
exit 1 | |
} | |
# Check that the user has provided the correct number of arguments | |
if [ $# -lt 1 ]; then | |
usage | |
fi | |
FOLDER_PATH=$1 # e.g. /Movies/MyMovie/Subtitles | |
# Check that the user has provided the correct arguments | |
function check_input() { | |
if [[ -z "$FOLDER_PATH" ]]; then | |
echo "Please provide a folder path as the single argument to this script." | |
echo "All files in the selected folder will be converted to UTF-8 encoding." | |
exit 1 | |
fi | |
if [[ ! -d "$FOLDER_PATH" ]]; then | |
echo "Folder does not exist" | |
exit 1 | |
fi | |
} | |
# Convert all files in a folder to UTF-8 encoding | |
# e.g. ISO-8859-1 to UTF-8 | |
function subtitle_convert() { | |
check_input | |
echo "Converting all files in '$FOLDER_PATH' to UTF-8 encoding" | |
find "$FOLDER_PATH" -type f -print0 | while IFS= read -r -d '' file; do | |
if [[ $file == *.srt ]]; then | |
# Grab the character encoding using file and awk | |
# On macOS Darwin, use: `file -bI` | |
# For other Unix distributions, use (lowercase i): `file -bi` | |
charset="$(file -bI "$file" | awk -F "=" '{print $2}')" | |
if [ "$charset" != utf-8 ]; then | |
iconv -f "$charset" -t utf-8 "$file" >"$file.new" && | |
mv -f "$file.new" "$file" && | |
echo "$file" | |
fi | |
fi | |
done | |
exit 0 | |
} | |
subtitle_convert |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment