20

I have a situation where I need to daily go over 400+ files in a folder on Xsan and replace spaces with under-scores in the filenames of the files.

Does anyone one have a script at hand that I can run via the terminal for example that will do this for me?

UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
Ronny vdb
  • 2,324
  • 5
  • 32
  • 74

1 Answers1

49

Here you go, this loops through all files (and folders) in the current directory:

for oldname in *
do
  newname=`echo $oldname | sed -e 's/ /_/g'`
  mv "$oldname" "$newname"
done

Please do note that this will overwrite files with the same name. That is, if there are two files that have otherwise identical filenames, but one has underscore(s) where the other has space(s). In that situation, the one that had underscores will be overwritten with the one that had spaces. This longer version will skip those cases instead:

for oldname in *
do
  newname=`echo $oldname | sed -e 's/ /_/g'`
  if [ "$newname" = "$oldname" ]
  then
    continue
  fi
  if [ -e "$newname" ]
  then
    echo Skipping "$oldname", because "$newname" exists
  else
    mv "$oldname" "$newname"
  fi
done
Ilari Scheinin
  • 776
  • 9
  • 14
  • What is the function of the double quotes in the mv command? Is that line equivalent to mv $(oldname) $(newname)? – K. Shores Aug 11 '16 at 04:16
  • Without the double quotes, filenames with spaces would cause problems. And no, not equivalent. The `$()` syntax is for command substitution: https://en.wikipedia.org/wiki/Command_substitution – Ilari Scheinin Aug 22 '16 at 10:48