Search code examples
bashscriptingfind

Find the highest number value in file names


I've been doing research for 3 days now, so I'm putting my question here. I have a script that I use to standardize my TV series. In the end, everything looks like this syntax: ([\w\d\s]+)(_S(\d{2})E)(\d{1,3}) Here's an example: Here it all begins_S01E51.mkv

I'd like to find and rename the last episode of the season. Example: Here it all begins_S01E51 - Final.mkv

Could someone help me find a solution? Thank you very much!


Solution

  • Loop over the files, use parameter expansion to extract the episode number. Store the maximum in a variable.

    #!/bin/bash
    max=0
    for f in 'Here it all begins_S01E'*.mkv ; do
        n=${f##*E}   # Remove everything up to the last E.
        n=${n%.mkv}  # Remove the extension.
        if (( n > max )) ; then
            max=$n
        fi
    done
    echo 'Here it all begins_S01E'$max.mkv
    

    To make it work over series and seasons, too, extract the series and season in a similar way. Now we need to store a maximum per series and season, we can take advantage of an associative array for that.

    #!/bin/bash
    declare -A season
    for f in *.mkv ; do
        series=${f%%_S[0-9]*}
        s=${f##*S}
        s=${s%%E*}
        e=${f##*E}
        e=${e%.mkv}
        if (( e > season[${series}_S$s] )) ; then
            season[${series}_S$s]=$e
        fi
    done
    for s in "${!season[@]}" ; do
        echo "${s}E${season[$s]}.mkv"
    done