Bash: Looping through Files with Spaces

I was trying to move some miscellaneous music files into directories by artist name. The files (and folders) have spaces in the file names. For my first attempt I tries a for loop e.g.
for file in $(find /path/to/music -type f); do

done
A for loop will not do this regardless of how much you escape or quote. To solve this problem use ‘while’ e.g.
findĀ  /path/to/music -maxdepth 1 -type f | while read file; do

done

Finished script:

#!/bin/bash
TARGETDIR=/home/jonny/Music
cd $TARGETDIR
#awk -F" - " '{print "\""$1"\""}'
find $TARGETDIR -maxdepth 1 -type f | while read file; do
artist=`echo "${file}" | awk -F" - " '{print $1}'`
echo "artist is: "$artist
echo "file is : "$file
if [ -d "${artist}" ]; then
echo "Directory already exists...moving file..."${file}
mv "$file" "$artist"
else
echo "CREATE "$artist
mkdir "$artist"
mv "$file" "$artist"
fi
done

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>