0

I wrote this code to make an Array containing my images:

listOfImages=(`find . -iname "*.png" 2>/dev/null`)

But the path could have spaces in it so I have to enclose every element in double quotes:

listOfImages=(`find . -iname "*.png" 2>/dev/null | sed -E -e 's/(.*)/"\1"/'`)

Normally when we print an Array's elements, it should not print the double quotes, example:

x=("a" "b")
for i in ${x[@]}
do
echo "$i"
done

And it prints:

a
b

But on my images Array, it prints with the double quotes which causes problems on the following codes on my script.

Demonstration:

for i in ${listOfImages[@]}
do
echo $i
done

And it prints:

"blocks/glass.png"
"blocks/glass_black.png"
Shayan
  • 709
  • 1
  • 15
  • 31
  • 1
    `mapfile -t -d '' listOfImages < <(find . -iname '*.png' -type f print0)`, also quote your variables, `"${listOfImages[@]}"` not `${listOfImages[@]}` – Jetchisel Apr 09 '20 at 08:50
  • 1
    You'll also need to quote the array uses (`for i in "${x[@]}"`) – Mat Apr 09 '20 at 08:54
  • @Shayan : But you have put the double quotes there yourself, when you did the `"\1"` in your `sed` command1 – user1934428 Apr 09 '20 at 10:12
  • @user1934428 I also put double quotes on this line: `x=("a" "b")` but they didn't get printed, see? – Shayan Apr 09 '20 at 10:22
  • This is completely different. Your sed command has been enclosed in single quotes, but here you haven't. If you had written `x=('"a"' "b")`, you would have seen the double quotes around `a`, but not `b`. – user1934428 Apr 09 '20 at 10:25
  • @user1934428 Read the `sed` documents. – Shayan Apr 09 '20 at 10:32

1 Answers1

1

The double quotes in the output of your sed command have no syntactical meaning, i.e. they don't delimit the start and end of filenames. They're just literal quotes in the strings that go into your array. They don't protect you in any way from a filename like my image.png becoming two elements in your array.

Before making things more complicated, I'm wondering if you can use globstar to do a recursive expansion and get all your files ending with .png:

shopt -s globstar # enable recursive expansion of **
listOfImages=( **/*.png )

You almost always should loop through an array like:

for img in "${listOfImages[@]}" # quotes around the expansion

These quotes have syntactic meaning and prevent word-splitting from happening to the elements in your array, so my image.png is treated as a single element in the list.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141