Issue
I've been working on my first Bash script which generates .nfo
files using the corresponding file names in a given directory. Using code I've found elsewhere, I've been able to achieve this and also include the following text within each .nfo
file:
<episodedetails>
<title>This is working successfully</title>
<episode>This bit however is not working</episode>
<season>This bit however is not working</season>
</episodedetails>
What I'm struggling with is the Episode and Season fields within the nfo
file.
My file name format is like this: Holy Bible - The Book of Ephesians (2009) - S01E01 (Introduction, Background, God's Blueprint).vob
The output of that particular nfo
file (at present) is:
<episodedetails>
<title>Introduction, Background, God's Blueprint</title>
<episode>2009)</episode>
<season>The Book of Ephesians (2009)</season>
</episodedetails>
Please could you help me tweak my code so that the nfo
reads:
<episodedetails>
<title>Introduction, Background, God's Blueprint</title>
<episode>01</episode>
<season>01</season>
</episodedetails>
The specific area of code that's going wrong is as follows:
episode="${filename#* - *(}"
episode="${episode% - *.vob}"
season="${filename#* - }"
season="${season% - *.vob}"
The code in its entirety:
#!/usr/bin/env bash
while IFS= read -rd '' file; do
filename="${file##*/}"
title="${filename%\).vob}"
title="${title##* (}"
episode="${filename#* - *(}"
episode="${episode% - *.vob}"
season="${filename#* - }"
season="${season% - *.vob}"
cat > "${file%\.vob}.nfo" <<< \
"<episodedetails>
<title>${title}</title>
<episode>${episode}</episode>
<season>${season}</season>
</episodedetails>"
done < <(find . -name '*.vob' -print0)
Solution
bash
has a nice =~
operator of the [[ ... ]]
conditional expressions that is handy in such cases. It tries to match a string (your file name) with a regular expression, and supports capture groups. The captured matches are available in the BASH_REMATCH
indexed array. Example of use in your case:
while IFS= read -rd '' file; do
[[ "$file" =~ ^.*-\ S([0-9]+)E([0-9]+)\ \((.*)\)\.vob$ ]] &&
cat > "${file%\.vob}.nfo" <<< \
"<episodedetails>
<title>${BASH_REMATCH[3]}</title>
<episode>${BASH_REMATCH[2]}</episode>
<season>${BASH_REMATCH[1]}</season>
</episodedetails>"
done < <(find . -name '*.vob' -print0)
Answered By - Renaud Pacalet Answer Checked By - Senaida (WPSolving Volunteer)