2

So im trying to rename all files in a directory, so that they do not have spaces. Im doing a bash script and im really not sure what to do, i've tried all kinds of quotes and escaping but im not sure what combo could work.

#!/bin/bash
#change empty spaces in filenames to underlineos
lsarray="$(echo "$(pwd)""/*")"
for i in $lsarray
do
    if [[ $i == *" "* ]] 
    then
        line=$(echo $i | sed 's/ \+/\_/g')
        j=$(echo $i | sed 's/ \+/\\ /g')
        mv "$j" "$line"
        echo "$i"
        echo "$j"
        echo "$line"
        fi
done

since mv needs "special variable expansion" im using double quotes on it. Any tips appreciated.

muru
  • 69,900
  • 13
  • 192
  • 292
user198918
  • 21
  • 1
  • 2

2 Answers2

7

Into bash for all the files into folder.

for name in *; do mv "$name" "${name// /_}"; done

The ${name/pattern/replace} replaces pattern to replace (Bash Parameter Expansion). If pattern starts with / (here pattern is / + Space), it replaces all the occurencies. Then mv renames file from name to new name with replaced spaces.

Konstantin Morenko
  • 1,438
  • 1
  • 9
  • 8
4

With Perl's rename:

rename 'y/ /_/' *
Cyrus
  • 12,059
  • 3
  • 29
  • 53