9

Through terminal I can't access files or directories with a spaces in their names. The cd command says no such file or directory.

Is there any way to do it or should I rename all files with spaces?

marked as duplicate by dessert, waltinator, ravery, Eliah Kagan, Zanna Dec 10 '17 at 7:46

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.

9

To access a directory having space in between the name use \<space> to access it. You can also use Tab button to auto completion of name.

For example :

guru@guru-Aspire-5738:~$ cd /media/Data/My\ Data/
guru@guru-Aspire-5738:/media/Data/My Data$.
  • 3
    You can also use quotes around the directory name, as in cd /media/Data/"My Data"/ – Charles Green Aug 27 '14 at 15:56
  • Yes @Charles. It will also work – g_p Aug 27 '14 at 15:57
3

To to use files with spaces you can either use the escape character or youse the double quotes.

example:

cd new\ dir/

\ is called escape character, used to not expansion of space, so now bash read the space as part of file name.

Or you can use:

cd "new dir" 

Now to rename files, it's so easy to rename all files with spaces and replace space with underscore:

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

look at answer here there is a script to rename all files and dirs recursively.

The script is:(All rights go to its owner)

#!/bin/bash

# set -o xtrace # uncomment for debugging

declare weirdchars=" &\'"

function normalise_and_rename() {
  declare -a list=("${!1}")
      for fileordir in "${list[@]}";
      do
          newname="${fileordir//[${weirdchars}]/_}"
          [[ ! -a "$newname" ]] && \
            mv "$fileordir" "$newname" || \
                echo "Skipping existing file, $newname."
      done
}

declare -a dirs files

while IFS= read -r -d '' dir; do
    dirs+=("$dir")
done < <(find -type d -print0 | sort -z)

normalise_and_rename dirs[@]

while IFS= read -r -d '' file; do
    files+=("$file")
done < <(find -type f -print0 | sort -z)

normalise_and_rename files[@] 

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