Page 1 of 1

Changing directory names that contain spaces

Posted: 2021-Jul-25, 12:48 pm
by MigrationUser
07 Dec 2011 15:34
pittendrigh


I frequently get DVDs (usually images) from customers who want me to create an image gallery.
Filenames and directory names that contain spaces are annoying.

A simple sedfilenames script is easy.
Changing directory names is more difficult.

First stab (with param checking and usage omitted) below.
The following blows up because a $dir named "my images" evalutates to "my" in the mv line.

Code: Select all

find $searchwhere -depth -type d -name "*$changefrompattern*" | while read dir;
do
   base=`basename "$dir"`
   dirname=`dirname "$dir"`
   newbase=`echo "$base" | sed "s/$changefrompattern/$changetopattern/g"`
   mv "$dir" "$dirname/$newbase"   
done
This seems to work ....although I don't know why

Code: Select all

find $searchwhere -depth -type d -name "*$changefrompattern*" | while read dir;
do
   base=`basename "$dir"`
   dirname=`dirname "$dir"`
   newbase=`echo "$base" | sed "s/$changefrompattern/$changetopattern/g"`
   mv "$dir" "$dirname/$newbase"
done
QUESTIONS
1) Is there any way to make the first failed attempt (using a for find loop) to work?
2) What is it (in the second loop that does work) about find pipe to while read that makes things work as desired?

----------------------------


#3 07 May 2012 13:54
kevink


Try escaping the quotes, like this:

Code: Select all

mv \"$dir\" \"$dirname/$newbase\"
The quotes you're using aren't gaining you anything, because $dir and "$dir" are both going to evaluate to two strings instead of one.