2

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.

yogsma
  • 245
  • 1
  • 3
  • 12

1 Answers1

5

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.

Dom
  • 6,743
  • 1
  • 20
  • 24
  • 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