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.

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

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

  • 1
    An easier solution might use find . -type f -exec in conjunction with rename.
    – phk
    Nov 6, 2016 at 15:17
  • The true word is underscore en.wikipedia.org/wiki/Underscore (I have edited)
    – aurelien
    Nov 6, 2016 at 15:46

2 Answers 2


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.


With Perl's rename:

rename 'y/ /_/' *

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