Search code examples
bashshelldir

Rename more than one directory at once


I have bunch of directories such as

2013_03_12_18_26_am
2013_03_12_18_26_cu
2013_03_12_18_26_ig
2013_03_12_18_26_mdf
2013_03_12_18_26_pih
2013_03_12_18_26_tn
2013_03_12_18_26_an
2013_03_12_18_26_cv
2013_03_12_18_26_ik
2013_03_12_18_26_mhr
2013_03_12_18_26_pnb    
2013_03_12_18_26_to

What I want to do is rename them to their last two characters, example: 2013_03_12_18_26_am to am, I know I can do this one by one mv 2013_03_12_18_26_am am but that would take a long time. Can this be accomplis from the shell script?

I want everything after the last "_" to be the name of the new directory.


Solution

  • This assume all (and only all) of your folders are in one directory. So be careful...

    Original:

    marks-mac-pro:test mstanislav$ ls
    2013_03_12_18_26_am 2013_03_12_18_26_an 2013_03_12_18_26_cu 2013_03_12_18_26_cv     2013_03_12_18_26_ig 2013_03_12_18_26_ik 2013_03_12_18_26_mdf    2013_03_12_18_26_mhr    2013_03_12_18_26_pih    2013_03_12_18_26_pnb    2013_03_12_18_26_tn 2013_03_12_18_26_to
    

    Shell Script:

    marks-mac-pro:test mstanislav$ for i in `ls .`; do NEW=`echo $i | cut -d_ -f6`; mv $i $NEW; done
    

    Result:

    marks-mac-pro:test mstanislav$ ls
    am  an  cu  cv  ig  ik  mdf mhr pih pnb tn  to
    

    Please test this before doing it on the real data, just to make sure. Again, only do this in a directory with JUST the folders you want to rename, or re-write the first part for the ls to be more specific.