Ubuntu – Copying files from directories having spaces in its name

command linecp

This is what I tried.

inputFile=$(zenity --file-selection --title "Test" --text "Please select the file for analysis." | sed -e "s/ /\\\ /g")

I did the sed operation to replace white spaces with a \ and a whitespace to make the copying command to work. Then from the Zenity file selection GUI I have chosen a file so that the value inside inputFile is /home/username/Documents/Learning\ and\ Development/testfile.txt.

Now when I try to copy this file to my working directory with

cp $inputFile .

Still it returns the error,

cp: cannot stat ‘/home/user/Documents/Learning\\’: No such file or directory
cp: cannot stat ‘and\\’: No such file or directory
cp: cannot stat ‘Development/WhatsApp.apk’: No such file or directory

Is there any way to bypass this? Actually I am writing a program. So I don't want to tell the users to rename their folder names to avoid spaces.

Best Answer

Easily you can do the trick, enclose by double quotes:

cp "$inputFile" /destination/

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, Read more: http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html

Related Question