0

I have a file hierarchy resembling this:

a0/files/x.txt
a1/files/y.txt
a2/files/z.txt

and I need to make these two arrays:

labels=("a0" "a1" "a2")
paths=("a0/files/x.txt" "a1/files/y.txt" "a2/files/z.txt")

This is what I did:

labels="a*"
paths=(); for d in $labels; do f=$(find $d -name "*.txt"); paths+="${f}"; done

labels is fine, but paths comes out as all the paths concatenated into a string, i.e. a0/files/x.txta1/files/y.txta2/files/z.txt rather than an array of paths. What am I doing wrong? bash v. 4.1.2.

wkc
  • 76
  • 4
  • 1
    Does this answer your question? [Add a new element to an array without specifying the index in Bash](https://stackoverflow.com/questions/1951506/add-a-new-element-to-an-array-without-specifying-the-index-in-bash) TL;DR: you are not appending to the array correctly. What you are doing adds to the first element in the array. Arrays in bash are weird. – jeremysprofile Sep 09 '20 at 19:26
  • Parens. The `+=` requires parens. – Paul Hodges Sep 09 '20 at 20:16
  • You might also want to limit your pattern to `a?` or even `a[0-9]`; if needed, activate extended globbing with `shopt -s extglob` and you can use `a+([0-9])`, as in `echo a+([0-9])` which can match (for example) `a0 a1 a22 a333` but won't match just `a` or `aa1`. – Paul Hodges Sep 09 '20 at 20:23

0 Answers0