Bash Script – Move Files to Folders Based on Name

bashdirectoryfilenamesrename

I have this file/folder scheme:

/Aula
  /Aula01
  /Aula02
aula-01.1.mp4
aula-01.2.mp4
aula-01.3.mp4
aula-02.1.mp4
aula-02.2.mp4
aula-02.3.mp4

All the mp4 files are located in the root directory (Aula), which contains subfolders called Aula01, Aula02 and so on…

I'd like to move these files to their specific subfolder based on the two-digit number in the middle of the files' name and on the final part of the subfolders' name. Like this:

/Aula
  /Aula**01**
    aula-**01**.1.mp4
    aula-**01**.2.mp4
    aula-**01**.3.mp4
  /Aula**02**
    aula-**02**.1.mp4
    aula-**02**.2.mp4
    aula-**02**.3.mp4

I've searched around and I've found this script, but my knowledge is too limited to tweak it.

#!/bin/bash
for f in *.{mp4,mkv}           # no need to use ls.
do
    filename=${f##*/}          # Use the last part of a path.
    extension=${f##*.}         # Remove up to the last dot.
    filename=${filename%.*}    # Remove from the last dot.
    dir=${filename#tv}         # Remove "tv" in front of filename.
    dir=${dir%.*}              # Remove episode
    dir=${dir%.*}              # Remove season
    dir=${dir//.}              # Remove all dots.
    echo "$filename $dir"
    if [[ -d $dir ]]; then     # If the directory exists
        mv "$filename" "$dir"/ # Move file there.
    fi
done

Could someone help me out tweaking it, or helping with a better script for this situation?

Also is there a way to make the script to extract only the two-digits number regardless of the file name scheme, in case it differs from the ones in this example

Thanks!

Best Answer

You can extract the numbers by parameter expansion. ${f:5:2} selects the two characters from the fifth position of the variable $f.

#! /bin/bash
for f in aula-??.?.mp4 ; do
    num=${f:5:2}
    mv "$f" Aula"$num"/
done

To extract two digits from the filename if the position is not fixed, use

#! /bin/bash
for f in *.mp4 ; do
    if [[ $f =~ ([0-9][0-9]) ]] ; then
        num=${BASH_REMATCH[1]}
        mv "$f" Aula"$num"/
    else
        echo "Can't extract number form '$f'" >&2
    fi
done
Related Question