I have folders named ACB* and in it among many other files, a couple of files called scanAC_*

I want to delete the part called scanAC and replace it with the directory name it is in.

For example, directory ACB_200315 containes file scanAC_typefile_2S.dcm, I want that lastfile to become ACB_200315_typefile_2S.dcm

What I have tried right now (Linux, SSH, rename option not available) but does not work:

for i in ACB*; do
cd ${i}
  mv scanID* ${i/scanID/${PWD##*/}};
cd ..
  • You need to add a second loop which loops over the files in the dir and then mv each file, one by one. mv with more than two args expects last arg to be a directory and moves all files into that directory. You cannot use mv scanID*
    – bsd
    Jan 28, 2016 at 10:46
  • You also use scanID in your script, yet list filenames as scanAC in question text.
    – bsd
    Jan 28, 2016 at 10:55
  • Yes these names are different on different servers, fortunately only requires me to change those two letters in the script to get it working on both. Thanks for the heads up.
    – SSK
    Jan 28, 2016 at 11:06

2 Answers 2


Got it working using the following script, adapted the one provided by Costas which did not work at first:

for d in ACB*; do
  cd ${d}
    for f in scanID*; do
    mv "${f}" "${d}${f#scanID}" 
  cd ..

For "couple of files" script have to be modified a little

for d in ACB* ; do
    for f in ${d}/scanID* ; do
        mv "${f}" "${f/scanID/${d}}"
       #mv "${f}" "${d}/${d}${f#*scanID}"

Or use find instead

find ACB* -name 'scanID*' -exec bash -c 'mv "$0" ""${0/scanID/${0%\/*}}"' {} \;
  • This does not work, output using echo is: mv ACB_200315/ACB_200315/scanID_typefile_2S.dcm ACB_200315/ACB_200315ACB200315/scanID_typefile_2S.dcm
    – SSK
    Jan 28, 2016 at 10:24
  • @SSK try new version
    – Costas
    Jan 28, 2016 at 11:11

You must log in to answer this question.

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