Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ls command

Status
Not open for further replies.

uguess

Technical User
Nov 5, 2004
40
CA
Hi Guys

I have a directory structure like below
ac123
ac123456
ac123456
ac134
ac134455
ac194
ac1946778

I want to rename all the directories and its files starting with ac into ab. How can i do this.

I tries outputting ls *.* > list
then renaming them. However the ls produces output that is not in full path format. Is there a better and faster way of renaming all these files.


Thanks
 
Code:
for i in ac*
do
  if [ -d $i ]
  then
    mv $i $(echo $i | tr 'c' 'b')
    for j in $(echo $i | tr 'c' 'b')/ac*
    do
      mv $j $(echo $j | tr 'c' 'b')
  done
done
This assumes your directory structure is exactly as described - i.e only one layer deep.

Columb Healy
 
Code:
# make destination dirs
find ac* -depth -type d | while read NAME
do
        NEWNAME=$(echo ${NAME} | sed 's/\<ac/ab/g')
        [[ ! -d ${NEWNAME} ]] && mkdir -p ${NEWNAME}
done
# move and rename files
find ac* -depth -type f | while read NAME
do
        NEWNAME=$(echo ${NAME} | sed 's/\<ac/ab/g')
        mv ${NAME} ${NEWNAME}
done
# remove source dirs
rm -r ac*

This should work for any depth of directory structure, and will only change 'ac' if it occurs at the beginning of the file or directory name (the '\<' in the sed search expression ties it to the beginning of a word).

Annihilannic.
 
A couple of points I thought of after my previous post. It is a Korn shell script, so should have #!/bin/ksh on the first line.

Also, you don't want to do that last step if the directories contain other files that aren't called ac*. :)

Another, perhaps safer, recursive solution:

Code:
#!/bin/ksh

recursive_rename() {
        ls -d $* | while read NAME
        do
                [[ -d ${NAME} ]] && (cd ${NAME} ; recursive_rename ac*)
                mv ${NAME} $(echo ${NAME} | sed 's/\<ac/ab/g')
        done
}

recursive_rename ac*


Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top