Results 1 to 4 of 4

Thread: Bash: Spaces in filenames get broken in array

  1. #1
    Join Date
    Feb 2007
    Location
    Everywhere
    Beans
    1,529
    Distro
    Ubuntu Development Release

    Bash: Spaces in filenames get broken in array

    Code:
    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?
    "Knowledge is power. Who said that?" - Dave Lister

  2. #2
    Join Date
    Feb 2007
    Location
    Romania
    Beans
    Hidden!

    Re: Bash: Spaces in filenames get broken in array

    Code:
    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:
    Code:
    IFS=$'\t\n'
    files=($(find $FOLDER -iname "*.jpg" -o -iname "*.gif" -o -iname ".png" -o -iname "*.bmp"))
    unset $IFS #or IFS=$' \t\n'
    Last edited by sisco311; March 17th, 2009 at 12:59 PM.

  3. #3
    Join Date
    Sep 2006
    Beans
    2,914

    Re: Bash: Spaces in filenames get broken in array

    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
    Code:
    # find "$FOLDER" \( -name "*.jpg -o -name "*.png" \) -print | while read FILE
    do
     # do something with $FILE
    done

  4. #4
    Join Date
    Feb 2007
    Location
    Everywhere
    Beans
    1,529
    Distro
    Ubuntu Development Release

    Re: Bash: Spaces in filenames get broken in array

    Thanks guys. Both solutions are very useful but the array is necessary in other scripts where I need to refer to it later.
    "Knowledge is power. Who said that?" - Dave Lister

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •