Hi I have a bunch of files with spaces in the name, is there a way to mv them to new files without spaces in. For example I have the file Hello World.pdf I want to move it to Hello_World.pdf. Obviously for the one file I can use the mv command but I want to do it to all files in a folder.

Thanks

link|improve this question

75% accept rate
I suspect an X-Y problem here. Could you tell us why you need to replace those spaces at all? – geek Apr 13 '10 at 16:37
feedback

3 Answers

up vote 8 down vote accepted

You can use the tr or sed commands for this:

for file in *.pdf
do
    newname=$(echo $file | tr ' ' _)
    mv "$file" $newname
done

Note that this uses the newer POSIX syntax for command substitution: $(command).
If you're using a really old Bourne shell, you'll need to use backticks:

newname=`echo $file | tr ' ' _`
link|improve this answer
feedback

Here are couple of scripts I use for this task:

#!/bin/ksh
# Name     : unspace - replace spaces by underscores in file names
# Usage    : unspace [file ...]
# Example  : unspace *.doc
unspace()
{
  ls "$@" | while a=$(line)
  do
    file=$(echo $a | grep " ")
    if [ -n "$file" ]
    then
      file="$(print "$file" | sed 's/ /_/g')"
      print "$a" "->" "$file"
      mv "$a" "$file"
    fi
  done
}
[[ "$(basename $0)" = unspace ]] && unspace "$@"

The following one is recursively fixing all names under the current directory. Note that it still need some work if directory names contain embedded spaces too.

#!/bin/ksh
find . |
  while a=$(line)
  do
          newName="$(print $a | tr ' ' '_')"
          if [ "$a" != "$newName" ]
          then
                  mv "$a" "$newName"
                  print $a moved
          else
                  print $a unchanged
          fi
  done
link|improve this answer
feedback

if you have bash, no need to call external tools

for file in *.pdf
do 
  if [ -f "$file" ];then
     echo mv "$file" "${file// /_}"
  fi
done
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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