I have to rename directories under the root directory with prefix "ms_PF" and then rename their subdirectories with the modified name of the main directory with an extra "_", and then copy all directories and their subs to root as follows:


maindir1 and maindir2 to be renamed with prefix "ms_PF_" and copied direct to root, because maindir2 has subdirectories they will carry the new name of maindir2 which is ms_PF_maindir2 plus and underscor (_) then all subs will be copied to root as follows:


Assistance in this matter is highly appreciated. My attempted solution is something like this, but it actually needs fixing:

do_it () {
awk '{ print "mv $root_dir $prefix ${root_dir/\//_}" }' | sh
find "$root_dir" -depth -type d | do_it

If it is only a few directories, do it by hand (anything else will be more work in writing/debugging than in doing).

If it is a largeish set, use find(1) to create a list of the affected files, and use your favorite editor to transform that into a script doing the moving. Check it for mistakes, and fire away.

If even larger/repetitive, I'd do essentially the same as the above, but do the "edit the path into the new name" by sed(1) on-the-fly. Perhaps even called directly from find. Would make a nice one-liner to scare newbies witless...

| improve this answer | |

This will do the renaming in the right order. Note the trailing slash in the first pattern limits the matches to directories.

cd root
for dir in maindir*/*/ maindir*; do
    echo mv $dir ms_PF_${dir/\//_}


mv maindir2/subdir1/ ms_PF_maindir2_subdir1/
mv maindir2/subdir2/ ms_PF_maindir2_subdir2/
mv maindir2/subdir3/ ms_PF_maindir2_subdir3/
mv maindir1 ms_PF_maindir1
mv maindir2 ms_PF_maindir2
| improve this answer | |
  • Thank you Glenn for your promptness and sincere help. In fact, I ran your script as it is with modifying root and maindir values, but got "${root/...}: Bad substitution". Any suggestions? – terry Mar 8 '13 at 7:07
  • Please put your code up in the question so you can format it properly – glenn jackman Mar 8 '13 at 13:38
  • Sorry Glenn for the mess I made in your solution. However, I put my attempted script up in the question as you asked; hope it makes sense in concept, but it does need to be looked into. I do appreciate your help, thank you. – terry Mar 8 '13 at 15:33
  • @terry If you're satisfied with glenn's script, remove the echo to actually perform the moves. – Gilles 'SO- stop being evil' Mar 8 '13 at 16:00
  • Thanks Gilles, I've actually done so getting the same msg: ${dir/...}: Bad substitution. Due to having to do this task, I've been reading a lot as my main expertise is in mobile tech! So any assistance is highly appreciated. – terry Mar 8 '13 at 16:22

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.