Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am currently writing a bash script and I have obtained a list of file locations. However I have notice that some file locations have spaces in the file name such as eg. : /1 2 3.txt Such files affects the use of commands such as cp in my case. Using "" and escaping it results in a space after the "". For e.g: " /1 2 3.txt" with a space in front of the file location, i obtained an error stating "cp: cannot stat ` /1 2 3.txt': No Such file or directory ". Is there any other method to quote a file location with "" so that the cp command can be used?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Copy all files containing spaces inside filenames in the new files with the same name containing underscores instead of spaces from the current directory:

for f in *\ *; do cp -- "$f" "${f// /_}"; done

See BashFAQ 20 on how to handle filenames safely.

share|improve this answer
    
Thanks for the help! I was thinking of writing a loop to replace it but i didn't want to alter the file name. I guess I will stick to your idea as the use of quotes such as "" is affecting my file location. –  pikachu Jul 25 '13 at 7:35
    
i removed the for loop and used the "cp -- "$f" "${f// /_}";" it works on the cmd however when it is implemented in my bash script i received a "cp: cannot stat ` /1 2 3.txt': No such file or directory" error. Do you know why there is a large space inserted into the file location? –  pikachu Jul 25 '13 at 9:20
    
@pikachu See BashFAQ 20 on how to handle filenames safely. –  Radu Rădeanu Jul 25 '13 at 9:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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