Move files to specific folders based on name

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x