This is my first post on StackOverflow. Be gentle. :)
I have a linux server that I download television shows to and manually move the files to their respective folders for my Plex server to utilize. I would like to automate this process. I have gotten as far as below.
File naming convention Show.Name.SeasonNumberEpisodeNumber.HDTV.X264.etc...
Example: Almost.Human.S01E01.720p.HDTV.X264.mkv
NOTE: The Show name can be different lengths with a . between each word in the name.
I am able to extract the show folder name from the filename.
#!/bin/bash
readonly FILEPATH=~/downloads
readonly SAVEPATH=~/shows
for file in $FILEPATH/*.mkv
do
#Get foldername from filename (everything before .S0 is foldername
foldername=$(basename "${file%.S0*}" | tr '.' ' ')
#Need to convert extracted season info into folder name ex. S01 = Season 1
# seasonfolder=$(basename "${file}" | sed -e 's/^[^S0]*//;')
#Copy the file to the path we built.
#Auto-create folder if it doesn't exist?
# cp $file "$SAVEPATH/$foldername/#seasonfolder"
done
Issues:
- I would like to also extract the season information from the filename and use it to build the rest of the folder path. Each file has a SxxExx portion that I can use to get the Season info. I would convert, for example, S01 into Season 1 to be part of the folder path.
Resulting Copy command would look something like this (using above filename)
cp Almost.Human.S01E01.720p.HDTV.X264.mkv shows/Almost Human/Season 1
I am not savvy enough with sed or regex to get the syntax right and after lots of searching, no one is quite doing this in any example I can "borrow" from.
Thanks in advance!
UPDATE
Much thanks to Janos! Not only did he provide an excellent solution, but helped me absorb a little more about using regex.
I made a few changes to the final product. After some research about Plex's naming convention requirements, I adjusted the regex to acommodate and also built in a "file exists" check to avoid unnecessary transfers.
Here's the final result that I will be adding to CRON later tonight.
#!/bin/bash
readonly FILEPATH=~/downloads
readonly SAVEPATH=~/shows
for file in $FILEPATH/*.mkv
do
dfile="$SAVEPATH/$(basename "$file" | sed -e 's/\./ /g' -e 's?\(.*\) [Ss]\([0-9][0-9]\)[Ee]\([0-9][0-9]\) .*?\1/Season \2/\1 - S\2E\3.mkv?')"
if [ ! -f "$dfile" ]
then
cp -v "$file" "$dfile"
mkdir -p "$(dirname "$dfile")"
else
echo "file exists "$dfile""
fi
done