Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

3 Answers 3

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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