How to access files/directories with spaces in the name? [duplicate]

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?


Solution 1:

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$.

Solution 2:

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[@]