LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Need to remove spaces from all file / dir names ?? Solution here! (https://www.linuxquestions.org/questions/linux-general-1/need-to-remove-spaces-from-all-file-dir-names-solution-here-207632/)

jsjohnst 07-20-2004 08:37 PM

Need to remove spaces from all file / dir names ?? Solution here!
 
Have you ever been faces with the problem of having a directory full of files and folders with spaces in them (take your MP3 collection for example)? Well here is an easy way to remove all those spaces and replace them with underscores. The only requirement is that you not have any files / directories with + signs in the name.

Code:

for i in `find . | tr "[:blank:]" "+" | grep "+"`; do echo "Changing Directory: " `echo $i | sed -r 's/\+/\\ /g'` " to " `echo $i | tr "+" "_"`;  mv "`echo $i | sed -r 's/\+/\\ /g'`" `echo $i | tr "+" "_"`; done
The above code will change all files in the current directory and all below it. If you get any errors, simply run the command again. Keep running it until the errors are gone and you should be set.

Tinkster 07-20-2004 09:17 PM

Code:

#!/bin/bash
IFS='
'
j=`find $1 -printf "%d\n" | sort -u | tail -n 1`
j=$((j-1))
echo "Max dir depth:" $j
for (( i=0; i<=j ; i++ ))
do
  for name in `find -mindepth $i -maxdepth $i -iname "* *" -printf "%p\n"`
  do
    newname=`echo "$name" | tr " " "_"`
    echo "$name" "$newname"
    mv "$name" "$newname"
  done
done

Not a one-liner, but hey ;)
No need to re-run because of errors ...

frob23 07-20-2004 09:39 PM

Ooohhh, I am saving this. I can't count the number of times a script has failed because of spaces that I could not find a way to get the shell to ignore.

Thanks guys.


All times are GMT -5. The time now is 02:12 PM.