Take the 2-minute tour ×
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:

images/dir1/subdir1/IMG/files.jpg
images/dir1/subdir2/IMG/files.jpg
images/dir1/subdir3/IMG/files.jpg
images/dir2/subdir1/IMG/files.jpg
.......
images/dir109/subdir1/IMG/files.jpg

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:

images/dir1/subdir1/file1.jpg
images/dir1/subdir1/file2.jpg
images/dir1/subdir2/file1.jpg
........
images/dir109/subdir1/file.jpg
share|improve this question
1  
Maybe something with prename. dev.man-online.org/man1/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.

#!/bin/bash

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

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.

#!/bin/bash

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

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

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 moveJPGsToParent.sh.
  2. Make it executable: chmod u+x moveJPGsToParent.sh
  3. Run it: ./moveJPGsToParent.sh "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

 
discard

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.