1

I am looping though a directory for a certain command; however, I do not know how to accommodate for spaces

#!/bin/bash

image=(`ls *.bmp *.jpeg *.jpg | sort`)
data=(`ls *.dat | sort`)

for ((i=0; i < ${#image[@]}; i++))
do
  echo ${image[$i]} ${data[$i]}
done

I ran this script and it returned

OIS032_OS.bmp Disc
OIS034_OS.bmp Cube
OIS035_OD.bmp 200x200_9-30-2010_OD
OIS035_OS.bmp _ILM_RNFLOb.dat
OIS036_OD.bmp OIS007_Optic
OIS036_OS.bmp Disc

I wanted the program to return this line

OIS016_OD.bmp  OIS016_Optic Disc Cube 200x200_OS _ILM_RNFLOb.dat 

How do I fix bash array to store what I need

data=(`ls *.dat | sort`) 
Sam Hosseini
  • 813
  • 2
  • 9
  • 17
user1462442
  • 7,672
  • 1
  • 24
  • 27

2 Answers2

6

Don't call ls; just use pattern matching to populate the array:

shopt -s extglob    # We'll use a more complicated glob to avoid needing to sort
image=( *.@(bmp|jpeg|jpg) )
data=( *.dat )

for ((i=0; i < ${#image[@]}; i++))
do
  echo ${image[$i]} ${data[$i]}
done
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thank You for your answer. I feeling little off today-added this line because stack overflow mininum character comment – user1462442 Sep 07 '12 at 18:44
  • 2
    Without requiring extglob, you can use [brace expansion](http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion): `image=( *.{bmp,jpeg,jpg} )` – glenn jackman Sep 08 '12 at 00:44
  • 1
    Compare `a=(*.{bmp,jpeg,jpg})` and `b=(*.@(bmp|jpeg|jpg))` for the three files `a.bmp`, `a.jpeg`, and `z.jpeg`. I used the extended pattern to mimic the sorting shown in the original question, while the brace expansion would result in 3 separate patterns that would undergo filename expansion separately. – chepner Sep 08 '12 at 05:06
  • Thank you guys. I for explaining the complexities of bash. I will always use it to help write my scripts. I am wondering why I am saying thank you twice – user1462442 Sep 21 '12 at 18:57
1

I believe but am not certain you can do what you want with readarray and MAPFILE.

I asked something similar like this: Bash declaratively defining a list to loop on

Here another similar answer link: https://stackoverflow.com/a/7220619/318174

Community
  • 1
  • 1
Adam Gent
  • 47,843
  • 23
  • 153
  • 203