Can someone help me figure out how to remove double spaces from directory names?

I'm using a service which gives me a directory structure of files whose names contain spaces. Sometimes the directory names contain double spaces, and some of my home grown scripts can't handle it.

I'd like a shell command combination which will rename the directories removing double space. Sort of like sed 's/ / /g'.

Luckily there are no children directories whose parents also need to be renamed.

I can find the candidates like this

sh> find ~/Downloads/Scala_Intro -name '*  *' -print 
/Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Running Average-362/Edward  Cacioppo_2973_assignsubmission_file_
/Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Implement histogram-3169/Edward  Cacioppo_3102_assignsubmission_file_

But when I try to use xargs to manipulate this sequence of lines, xargs substitution seems to remove the double space. Thus I cannot generate the command line mv old-name new-name

sh> find ~/Downloads/Scala_Intro -name '*  *' -print | xargs -I % echo %
/Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Running Average-362/Edward Cacioppo_2973_assignsubmission_file_
/Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Implement histogram-3169/Edward Cacioppo_3102_assignsubmission_file_

I was trying something like the following, but it doesn't work.

sh> find ~/Downloads/Scala_Intro -name '*  *' -print | xargs -p -I % mv  "%" `echo "%" | sed 's/  / /g'`
mv /Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Running Average-362/Edward Cacioppo_2973_assignsubmission_file_ /Users/jimka/Downloads/Scala_Intro/SCALAIN_E-Running Average-362/Edward Cacioppo_2973_assignsubmission_file_?...

Notice when xargs asks whether to execute the mv command, the doubled space has already been converted to a single space.

1 Answer 1


Instead of xargs and mv, I would prefer rename tool:

Depending on which rename tool you have:

find ~/Downloads/Scala_Intro -name '*  *' -exec rename -n '  ' ' ' {} +


find ~/Downloads/Scala_Intro -name '*  *' -exec rename -n 's/  / /' {} +

(Remove -n option (dry-run) to actually perform the renaming if you're happy with the output)

Or if you want to stick using mv (no xargs needed, find -exec will do):

find ~/Downloads/Scala_Intro -name '*  *' -exec sh -c 'mv "$1" "${1//  / }"' find-sh {} \;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.