PDA

View Full Version : Bash: Spaces in filenames get broken in array



phenest
March 17th, 2009, 12:33 PM
files=(`find $FOLDER | grep -i "\.jpg$\|\.gif$\|\.png$\|\.bmp$"`)

I'm using this line in a bash script to fill an array with file names. But the file names are getting broken up if there is a space in it, i.e

File names:
file name.jpg

another.bmp

here is another.gif
Array:
files[0]=file

files[1]=name.jpg

files[2]=another.bmp

files[3]=here

files[4]=is

files[5]=another.gif

How can I prevent this?

sisco311
March 17th, 2009, 12:49 PM
IFS=$'\t\n'
files=(`find $FOLDER | grep -i "\.jpg$\|\.gif$\|\.png$\|\.bmp$"`)
unset $IFS #or IFS=$' \t\n'

set the IFS (Internal Field Separator) variable so that it splits fields by tab and newline and don't threat space as a filed separator.



this should be faster:

IFS=$'\t\n'
files=($(find $FOLDER -iname "*.jpg" -o -iname "*.gif" -o -iname ".png" -o -iname "*.bmp"))
unset $IFS #or IFS=$' \t\n';)

ghostdog74
March 17th, 2009, 01:29 PM
no need to mess around with internal IFS. use a while read loop. Anyway, why do you need to put into arrays? Unless you are using your results later in your script, otherwise, just pipe your results to a while read loop for immediate processing. Also, there's no need to use grep. find can find specific file names


# find "$FOLDER" \( -name "*.jpg -o -name "*.png" \) -print | while read FILE
do
# do something with $FILE
done

phenest
March 17th, 2009, 02:02 PM
Thanks guys. Both solutions are very useful but the array is necessary in other scripts where I need to refer to it later.