Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
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
up vote 9 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 ' ' _`
share|improve this answer

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
share|improve this answer

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
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .