0

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!

4

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
  • Worked perfectly. Is there a way to adapt this script to extract only the two-digits number regardless of the file name scheme, in case it differs from the ones in this example? – André Luís Jun 26 at 16:26
  • Sure. It depends on the possible file names, though. Do you want to extract the first two digits, first two digits after a dash, or what? – choroba Jun 26 at 17:38
  • There will always be only one two-digits number in the file name. – André Luís Jun 26 at 17:44
  • 1
    You can try a regex match, then: [[ $f =~ ([0-9][0-9]) ]] ; num=${BASH_REMATCH[1]} – choroba Jun 26 at 18:00
  • How would that work in the script? Sorry, I'm not experienced on coding. – André Luís Jun 26 at 18:02

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.