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!

Replace characters in a directory name 1

Status
Not open for further replies.

chinobling

Technical User
Apr 28, 2005
5
US
Hi,

I'm trying to write a script to find directories/subdirectories with a certain pattern in the name, then replace the pattern in the directory name.

I figured out how to find them using find $1 -type d -name "*$2*" but it's the replacing that's giving me a migraine... please help!

TIA.
 
You want to replace $2 with what ?

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
i.e.:

./aa/aabb
./aabb/bbcc
./aabbcc/ccdd
./aabbccdd/ddee

would like to replace characters bb with zz or $3

Thanks.

 
find $1 -type d -name "*$2*" | sed "s/$2/$3/g"

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thnx for the replies, but how would i use the output of sed to move/rename the directories to the sed result?

Thnx again.
 
find $1 -type d -name "*$2*" | while read d
do mv "$d" $(echo "$d" | sed "s/$2/$3/g")
done

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
It didn't work
I got this an output...

mv: cannot move `./aa/bb' to a subdirectory of itself, `./aa/bb/bb'
mv: cannot move `./aabb' to a subdirectory of itself, `./aabb/aabb'
mv: cannot move `./aabbcc' to a subdirectory of itself, `./aabbcc/aabbcc'
mv: cannot move `./aabbccdd' to a subdirectory of itself, `./aabbccdd/aabbccdd'

Thnx for your help.
 
What are REALLY $2 and $3 ?
You may get rid of the g in the sed script.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Hey, You're awesome, i was screwing up the script by passing:
"*bb*" as $2 when it was already specified in the script as "*$2*" so that's what it was!

Thanks a lot!!!

 
You can't use slashes ([tt]/[/tt]) as the field separator in the [tt]sed[/tt] command because the directories have slashes too. Try it like...
Code:
find $1 -type d -name "*$2*" | while read d
do
    mv "$d" $(echo "$d" | sed "s|$2|$3|g")
done
Hope this helps.
 
Sam, hopefully nor $2 nor $3 contains /, so no problem.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top