bash and filenames with spaces
I have been trying to learn a little bash programming. I was trying to write a script for work, part of which involved handling all jpg files in a directory. My script falls over when the files it is trying to process have spaces in the filenames. I cannot find a way around but I realise that there must be one. This is what I have tried:
#!/bin/sh SOURCEDIR='/path/to/sourcedir/' DESTDIR='/path/to/destdir' cd $SOURCEDIR for i in `ls *.jpg` do cp $i $DESTDIR done This works fine unless any of the filenames have spaces so I tried: #!/bin/sh SOURCEDIR='/path/to/sourcedir/' DESTDIR='/path/to/destdir' cd $SOURCEDIR for i in `ls -Q *.jpg` do cp $i $DESTDIR done This also doesn't work. I have tried putting quotes around various different pars but without success. What am I doing wrong? |
for i in *.jpg; do cp "$i" /path/to/destdir; done
That should do it. This is basically what you have, just quoting the $i variable, and suited for the shell instead of a script file (you need to be in sourcedir of course). |
better yet is to convert all your filenames containing spaces to use underscores. You can try this in the directory with the space names:
#!/bin/bash ls | while read each do echo "$each" | grep "\ " >/dev/null 2>&1 if [ $? -eq 0 ] then newname=`echo "$each" | tr ' ' '_'` mv "$each" $newname echo "Renamed \"$each\" to $newname" fi done |
All times are GMT -5. The time now is 01:35 AM. |