Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move and rename files based on parent folder in Linux?

I have a folder named photos with the following structure:

00001/photo.jpg
00002/photo.jpg
00003/photo.jpg

I want to:

  1. Rename the file within the folder (which called photo.jpg) to parent folder.
  2. Move it a folder up.
  3. Remove the parent folder.

So the photos folder would be something like this:

00001.jpg
00002.jpg
00003.jpg

How can I do this in Terminal in Linux?

Note. There are 100000+ such folders in photos.

like image 985
user2480690 Avatar asked Jun 30 '13 06:06

user2480690


2 Answers

Post edited since I've read in a comment that you have 100000+ such directories.

Do not use any method that involves bash globbing, it would be terribly slow and inefficient. Instead, use this find command, from within the photos directory:

find -regex '\./[0-9]+' -type d -exec mv -n -- {}/photo.jpg {}.jpg \; -empty -delete

I've use the -n option to mv so that we don't overwrite existing files. Use it if your version of mv supports it. You can also use the -v option so that mv is verbose and you see what's happening:

find -regex '\./[0-9]+' -type d -exec mv -nv -- {}/photo.jpg {}.jpg \; -empty -delete

Read the previous command as:

  • -regex '\./[0-9]+': find everything in current directory that has only digits in its name
  • -type d: and it must be a directory
  • -exec mv -n -- {}/photo.jpg {}.jpg \;: move the photo.jpg file in this directory into the parent directory, with name: dirname.jpg
  • -empty: if the directory is now empty...
  • -delete: ...delete it.

After that, you might want to see which directories have not been deleted (because e.g., it contained more files than just the photo.jpg file):

find -regex '\./[0-9]+' -type d

Enjoy!

like image 70
gniourf_gniourf Avatar answered Oct 02 '22 02:10

gniourf_gniourf


cd $toTheRootFolderWhichYouHaveALLtheFolders #00001, 00002
mv 00001/photo.jpg 00001.jpg

Or you can use this bash script in the "photos" directory:

for entry in ./*; 
 do  
    mv "$entry"/photo.jpg "$entry".jpg ;
    rm -rf "$entry";
 done
like image 24
mrz Avatar answered Oct 02 '22 02:10

mrz