Shell script to rename multiple files from their parent folders name


I have a file structure like this:

  • 00000010
    • 000000001.file1
    • 000000001.file2
  • 00000020
    • 00000003.file1
    • 00000003.file2
    • 00000003.file3

So there are folders with 8-digit names containing one ore more files with name starting with 8-digit numbers. But theses filenames are – let's say – out of sync. So Now I try to rename them recursively in bash to archive:

  • 00000010
    • 000000010.file1
    • 000000010.file2
  • 00000020
    • 00000020.file1
    • 00000020.file2
    • 00000020.file3

My script does look like:

#! /bin/bash

find * -maxdepth 1 -name "*" -type d | while read -r dir
        rename 's/$dir\/[0-9]{8}/$dir/' *

But this is not working and gives errors like

Global symbol "$dir" requires explicit
package name at (eval 1) line 1.

How could I write it to rename the files according to their folder names?

Thank you for help!

Best Answer

As from another answer I learned, that I have to use

rename "s/$dir\/[0-9]{8}/$dir\/$dir/" $dir/*

Just in case anyone has the same problem...

Related Question