I'm trying to use find inside a loop to create a variable that contains a file matching the filename + desired string



This is the relevant part of the code:

shopt -s nullglob
shopt -s nocaseglob

if [ -d "$1" ]; then
    for file in "${1%/}/"*mkv; do
        # Get filename to match against subs and audios
        filename="$(basename "$file" .mkv)"

        # Find matching subtitle file
        engsubs="$(find . -name "$filename*en.srt*" | sed -e 's,^\./,,')"   

        # Find matching audio file
        engaudio="$(find . -iname "$filename*en.ac3" -o -iname "$filename*en.eac3" -o -iname "$filename*en.dts" | sed -e 's,^\./,,')" 

It works if files don't contain brackets, but the find commands don't find anything for files whose names contain brackets. Why this is happening? I want to create a variable like $en that would contain file1.en.srt


The problem is that [ and ] are glob characters. For example, consider this file:


When running your script on that file, $filename will be: ba[r] and therefore your find command will be:

find . -name 'ba[r]*pt-BR.srt*'

Since [r] is a single letter character class, it means r. So your command is looking for a filename starting with ba, then an r, then any character(s), and pt-BR.srt and any characters again. You need to escape the brackets:

find . -name 'ba\[r\]*pt-BR.srt*'

The simplest way to do that is to use printf and %q. So just change this line:

filename="$(basename "$file" .mkv)"

To this:

filename=$(printf '%q' "$(basename "$file" .mkv)")
  • Yeah I just noticed now that I didn't need that * at the end of srt or other file extensions lol. And it worked...thanks so much <3. Do you think this could mess with other filenames containing space, (), ç or other special characters? – Freedo Mar 25 at 9:42
  • 1
    @Freedo no, the spaces and ( will also be escaped. Try running printf '%q\n' "a ho[r]i(b)le file". – terdon Mar 25 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.