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

[Terminal] F2 – Command-line batch renaming tool

Project: https://github.com/ayoisaiah/f2
Wiki: https://github.com/ayoisaiah/f2/wiki
Installation: https://github.com/ayoisaiah/f2/wiki/Installation

curl -LO https://github.com/ayoisaiah/f2/releases/download/v1.6.1/f2_1.6.1_linux_amd64.tar.gz
tar -xvzf f2_1.6.1_linux_amd64.tar.gz 
chmod +x f2 
sudo mv f2 /usr/local/bin 
rm f2_1.6.1_linux_amd64.tar.gz 

Renaming a file from ‘img’ to ‘Image’

# test run
f2 -f 'img' -r 'Image'
# performing the actual renaming
f2 -f 'img' -r 'Image' -x
# undo the changes
f2 -u -x

Or renaming episodes from 01_S1.MyEpisode.mp4 to S01E01.MyEpisode.mp4

f2 -f '.._S1' -r 'S01E%02d'

[Shell] Replace pattern

How to replace a specific pattern in a file or folder name. In my case I needed to correct the season on each file of a series from “S08” to “S09”:

for f in *; do mv "$f" "$(echo "$f" | sed s/S08/S09/)"; done      

If you want to replace a pattern recursive, use the command “find”:

find . -name '*' -exec bash -c 'echo mv $0 ${0/S08/S09}' {} \;    // with echo for testrun