1

This question already has an answer here:

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.

marked as duplicate by don_crissti, steeldriver, HalosGhost, countermode, Jeff Schaller Nov 6 '16 at 16:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

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.

4

With Perl's rename:

rename 'y/ /_/' *

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