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};

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.


3 Answers 3


With zsh:

autoload zmv # best in ~/.zshrc
zmv '(XYZ??)(*)/(*)' '$1$2/$1$3'
  • Thank you, but is there a way to do this with ssh?
    – SSK
    Aug 28, 2015 at 10:38

With bash:

for f in XYZ*/*; do mv -v "$f" "${f%/*}/${f:0:5}${f##*/}"; done

The for loop runs trough all XYZ* directories. Then the mv command renames the files.


  • $f is the original filename
  • ${f%/*} is the directory name
  • ${f:0:5} is the prefix
  • ${f##*/} is the original filename

You can run this command which just shows you what it would do:

ls -d XYZ*/* |
sed -n s'|\(XYZ[0-9][0-9]\)\([^/]*\)/\(\2_.*\)|mv & \1\2/\1\3|p' |

and if you like the commands to run, replace cat by sh.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .