0

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

3

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 '  ' ' ' {} +

or

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 {} \;
2
  • Thanks, can you explain what find-sh is? Is that a bash-ism? Commented Jun 4, 2020 at 11:09
  • See unix.stackexchange.com/a/156010/236063 > "You should use something relevant there (like sh or find-sh)" Commented Jun 4, 2020 at 11:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.