Register
It is currently Tue Sep 30, 2014 9:50 am

batch rename of folders


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Thu Aug 19, 2010 1:33 pm   

Joined: Wed Jun 30, 2010 5:15 pm
Posts: 4
Hi All,

I need to rename a large set of folders based on a rule. I have a tab separated file (could be csv if needed) with two columns. One column contains the name of the folders as they exist. The 2nd column is what I want to rename the folder to. So the rule is:

1) Read the current folder name.
2) Try to match it in the first column. (needs to be exact match but case insensitive)
3) If match is found, rename folder to value in second column (just skip if no match found)
4) Repeat (one current directory is complete, do this recursively if possible)
5) Have a beer

-The folders have content so we can't risk deleting anything or renaming any files....just folder.
-Also, it would be great if this would work recursively. Once it finishes the current level, it would check each of the folders to see if they contain folders that could be matched and renamed.

I am completely stumped on how to do this. However, since I suck this is no surprise.... Thanks all!


Top
 Profile  
 PostPosted: Thu Aug 19, 2010 3:45 pm   
User avatar

Joined: Tue Apr 27, 2010 2:28 pm
Posts: 172
Location: Czech Republic
You can start from something along the following:
Code:
#!/bin/bash
names=$1
find -type d | tac | while read dir ; do
    if [[ $dir == '.' ]] ; then continue ; fi
    last=${dir##*/}
    path=${dir%/*}
    newname=$(grep -i "^$last"$'\t' $1 | cut -f2)
    if [[ $newname ]] ; then
        if [[ -e $path/$newname ]] ; then
            echo $path/$newname already exists, skipping $dir >&2
        else
            mv $dir $path/$newname
        fi
    fi
done

Use at your own risk. Not ready for spaces in folder names or / in the second column.
Homework: why is tac needed?


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 12 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP