eozzy
eozzy

Reputation: 68750

Move similar filenames to dir - Bash

I have several images with ID-sequence.jpg name where ID is same for a group of images, for example:

4fd-00027-1.jpg
4fd-00027-2.jpg
4fd-00027-3.jpg
6gq-00017-1.jpg
6gq-00017-2.jpg
6gq-00752-3.jpg
6gq-00752-4.jpg

... now I need to move all those files into their own directories which should also be named the same as ID. I believe I need something like this:

for FILE in *; do
ID_REGEX="(.*(?=-))"
if [[ $FILE =~ $ID_REGEX ]]; then
  ID="${BASH_REMATCH[1]}"
  echo "$ID"
  mkdir -p "/Users/myname/images_organized/$ID"
  $(mv "/Users/myname/images/$FILE" "/Users/myname/images_organized/$ID/$FILE" )
fi
done

... but its not doing anything. No errors either.

Upvotes: 0

Views: 72

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799370

Too much work.

for file in *
do
  dir="${file%%-*}"
  [ -d "$dir" ] || mkdir "$dir"
  mv "$file" "$dir"
done

Upvotes: 1

Related Questions