Sign up ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

i will try to explain my problem (sorry for my bad english).

I have an image gallery with a directory structure like that:


the directory named images contains 109 dirs (dir1,dir2, ... dir109), the 109 dirs totally have 1200 subdirs inside, every subdir contain a dir named IMG with images into it (file1.jpg file2.jpg etc ...), i would like to move all the images contained into every dir named IMG into the previous dir (subdir) to have something like that:

share|improve this question
Maybe something with prename. – Zoredache Dec 10 '12 at 15:40

1 Answer 1

I'm using Ubuntu, but this should work as long as you use bash.


for file in $(find ./images/ -name "file*.jpg"); do
    mv $file "$(dirname $file)/../"

Please note, for the purpose of simplicity this code does not handle spaces in path, so it may not work in other cases.

Edit: Here is probably a better code. To run it you have to specify absolute or relative path to the 'images' folder.


find "$1" -print | grep "IMG/file.*\.jpg" | while read file; do
    parent_dir="`dirname \"$file\"`/../"
    mv "$file" "$parent_dir"

find "$1" -name 'IMG' | while read IMG; do
    if [ -z "`ls -A \"$IMG\"`" ]; then
        rm -r "$IMG"

It takes care of spaces in path and removes the remaining and supposedly empty IMG directories. It removes IMG directory only if it is indeed empty. It should be also save to run this script multiple times.

In case you are very new to all this - here is how you use this code:

  1. Copy & Paste it to a new file, say
  2. Make it executable: chmod u+x
  3. Run it: ./ "path to images folder"

Edit 2: Should admit @Zoredache's solution turned out to be much more elegant:

rename 's/IMG\/file/file/' images/dir*/subdir*/IMG/file*.jpg

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.