Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[Terminal] Bash script to add leading season and episode numbers by parsing from file names

I had some videos in the format “My Episode #01.mkv” which I wanted to rename to “S01E01 My Episode #01.mkv“. This little script did the job for me:

# Specify the directory containing the files. For current directory use: $(dirname "$0")
directory="/path/to/your/directory"	

# Loop through all .mkv files in the directory
for file in "$directory"/*.{webm,mkv}; do
    # Check if the file exists to avoid errors when no files match
    [ -e "$file" ] || continue
    
    # Extract the base filename (without the directory path)
    filename=$(basename "$file")

    # Use regex to find the episode number (e.g., #01, #02)
    if [[ $filename =~ \#([0-9]+) ]]; then
        episode_number=${BASH_REMATCH[1]}

        # Pad the episode number with a leading zero if it's a single digit
        if [ ${#episode_number} -eq 1 ]; then
            episode_number="0$episode_number"
        fi  
		
        # Construct the new filename
        new_filename="S01E${episode_number} $filename"
        
        # Rename the file
        mv "$file" "$directory/$new_filename"
        echo "Renamed: $filename -> $new_filename"
    fi
done

Leave a Reply

Your email address will not be published. Required fields are marked *