Search code examples
bashdirectorymkdir

Moving images into folders with image filename


I have a folder called folder1 that has a bunch of pictures in it, and I would like to save each picture in an individual folder. The folder should have the same name as the file, for example if the picture is called "st123" I would like to create a folder called "st123" and move the picture into the folder. I have tried the following, but I get the error cannot move to a subdirectory of itself. Is there another way to solve this? Otherwise, would it be possible to save the image "st123" in a folder called "123" (so the last 3 characters)?

#!/bin/bash
Parent="/home/me/myfiles/folder1"
for file in $Parent; do
dir="${file%%.*}"
mkdir -p "$dir"
mv "$file" "$dir" 
done

Solution

  • This solution might be useful to you, though if you'd like to iterate over the images recursively I suggest you to use find. If that's indeed the case, let me know and I'll edit this answer with relevant code.

    for image in /home/me/myfiles/folder1/*; do
        if [[ -f $image ]]; then 
            newf="${image%%?([ab]).*}"
            mkdir -p "$newf"
            mv -- "$image" "$newf"
        fi
    done
    

    Test ( extglob is enabled ):

    $ [/home/rany/] touch test/st123a.tif test/st123b.tif test/st456.jpg test/st456b.jpg test/st789.tif
    $ [/home/rany/] for image in test/*; do newf="${image%%?([ab]).*}"; mkdir -p "$newf"; mv -- "$image" "$newf";done
    $ [/home/rany/] tree test
    test
    ├── st123
    │   ├── st123a.tif
    │   └── st123b.tif
    ├── st456
    │   ├── st456b.jpg
    │   └── st456.jpg
    └── st789
        └── st789.tif
    
    3 directories, 5 files
    

    EDIT:

    According to OP request I added the following changes:

    • Trim file-name's suffix a or b, so that, for example, file names st123a.ext and st123b.ext will go to the same directory st123. Important: this feature requires extglob enabled ( i.e. shopt -s extglob ).