Skip to content
Advertisement

Bash script to transfer all files from current directory to specific directory based on name

I have these files:

  1. 100-1.jpg
  2. 100-2.jpg
  3. 200-1.jpg
  4. 200-2.jpg

I want these to be transferred to specific folder based on filename

  1. 100/100-1.jpg
  2. 100/100-2.jpg
  3. 200/200-1.jpg
  4. 200/200-2.jpg

How do I do this?

What I have tried so far

cd ~/images
for f in *.jpg
do 
   mv -v "$f" ~/images/${f}/${f%}.jpg
done

how do I know I cut the string before the dash e.g 200-1 to 200 and store in a variable?

so I can do it like this

 cd ~/images
    for f in *.jpg
    name="$f without the .jpg"
    do 
       mv -v "$f" ~/images/${f}/${f%}.jpg
    done

Advertisement

Answer

#!/bin/bash
cd ~/images
for f in *.jpg
do
  mkdir -p ${f%-*}
  echo ${f%-*}
  mv "$f" ~/images/${f%-*}/${f%}
done
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement