Replace spaces in file names from cmd line unix

6

2

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

Aly

Posted 2010-04-13T11:12:30.357

Reputation: 195

I suspect an X-Y problem here. Could you tell us why you need to replace those spaces at all? – geek – 2010-04-13T16:37:18.497

Answers

10

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 ' ' _`

njd

Posted 2010-04-13T11:12:30.357

Reputation: 9 743

4

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

jlliagre

Posted 2010-04-13T11:12:30.357

Reputation: 12 469

0

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

user31894

Posted 2010-04-13T11:12:30.357

Reputation: 2 245