Linux – Move files from subdirectories into single directory and prefix original directory name

bashlinuxmvUbuntu

I have a directory structure like this:

./a/1.png
./a/2.png
./a/3.png
./b/1.png
./b/2.png
./b/3.png
./c/1.png
...

And I want to take all the files in the subdirectories and move them to a new directory so their names are something like

../dest/a_1.png
../dest/a_2.png
../dest/a_3.png
../dest/b_1.png
../dest/b_2.png
../dest/b_3.png
../dest/c_1.png
...

The closest I've been able to find without writing a script to do it file by file is to use find with the --backup=numbered option which would condense my files to a single directory but would end up losing the directory context from the filename.

Is there a succinct way to accomplish this?

Best Answer

With Perl's standalone rename command:

rename -n 's|/|_|; s|^|dest/|' */*.png

Output:

a/1.png renamed as dest/a_1.png
a/2.png renamed as dest/a_2.png
a/3.png renamed as dest/a_3.png
b/1.png renamed as dest/b_1.png
b/2.png renamed as dest/b_2.png
b/3.png renamed as dest/b_3.png
c/1.png renamed as dest/c_1.png

If everything looks fine, remove option -n.

Related Question