Shell – Rename files in directory according to name of directory

filesrenameshell

I am trying to rename a bunch of files according to the names of their directory in Linux, SSH.

I have a directory called XYZ01smith. In it are four files called smith_5*.I need to add prefix XYZ01 to these files.
But, the next directory is called XYZ02perry. In it are four files called perry_3*. I need to add the prefix XYZ02 to these files.

I have a loop to do this per directory:

for i in smith_5*;
    do mv ${i} XYZ01${i};
done 

But I have 50 directories (XYZ01name to XYZ50name), so I would rather be able to do this with one script for all 50. I am sure this should be possible, but I do not know how.

Best Answer

With zsh:

autoload zmv # best in ~/.zshrc
zmv '(XYZ??)(*)/(*)' '$1$2/$1$3'
Related Question