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 '16 at 10:46
  • You also use scanID in your script, yet list filenames as scanAC in question text. – bsd Jan 28 '16 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 '16 at 11:06

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 ..
| improve this answer | |

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%\/*}}"' {} \;
| improve this answer | |
  • 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 '16 at 10:24
  • @SSK try new version – Costas Jan 28 '16 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.