I have a folder named photos
with the following structure:
00001/photo.jpg
00002/photo.jpg
00003/photo.jpg
I want to:
photo.jpg
) to 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
.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With