How to handle files with their names containing spaces in a shell script.

Here is what I am trying

    find /abc/xyz -name 'BY567*.csv' | while read fname
    do
        mv "$fname" ./archive/$(basename $fname)-$(date +%Y%m%d-%T)
    done

But when I do this it strips of the file name after space. Like if file name is BY567_Test file.csv , it will be changed to BY567_Test-datetimestamp and not BY567_Test file.csv-datetimestamp.

link|improve this question

67% accept rate
feedback

1 Answer

up vote 5 down vote accepted

Put double-quotes arround the end of line and in basename :

mv "$fname" "./archive/$(basename "$fname")-$(date +%Y%m%d-%T)"

The variables will be interpreted and the spaces should be OK.

link|improve this answer
cool, it worked. Can I use the double quotes if I am using sftp to transfer the file to other server? Like in above loop if I am trying to connect to the other server and then using put $fname as command to transfer the file. – yogsma Oct 25 '10 at 16:02
I think so but, I never try. Try and tell us ! – Dom Oct 25 '10 at 16:08
It worked. Thanks – yogsma Oct 25 '10 at 20:15
feedback

Your Answer

 
or
required, but never shown

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