0

I am trying to create an array in bash that contains filenames for a subset of files stored in a single folder. I want the array to contain only filenames with the common string "zzz", and I want the array to contain one filename per element. I have been trying to use the find function to get filenames containing "zzz", and store the results in myarray.

Here is what I'm doing:

# Define folder containing files
file_dir=./my_files

# Define the common string
pattern="*zzz*"

# Store find output to myarray
readarray -d ' ' -t myarray < <(find ${file_dir} -name ${pattern})

# Print myarray
echo $myarray

Output:

./my_files/abc_zzz_1.nii.gz ./my_files/def_zzz_763.nii.gz ./my_files/ghi_zzz_628.nii.gz

myarray contains the correct filenames, however it does not appear to be structured in a way that allows indexing - I would like to be able to index the nth filename in myarray with ${myarray[n]}, however it seems that the full output from find is stored in a single element. echo ${myarray[0]} prints the same output as above, while echo ${myarray[1]} prints an empty line.

I figured that the whole output from find was being stored as a single string in ${myarray[0]}, so I tried to break the string up using:

read -r -a myarray2 <<< "${myarray[0]}"

...but this did not work as intended, because echo ${myarray2} only returns a single filename.

What am I doing wrong here?

Lyam
  • 123
  • 2
  • 14
  • 3
    Remove the `-d ' '`, quote your variables and Put a valid shebang and paste your script at https://shellcheck.net for validation/recommendation. – Jetchisel Oct 27 '22 at 18:04
  • 1
    If you do it _right_, `echo "$myarray"` will show only the first element. Use `declare -p myarray` to print your whole array in unambiguous form. – Charles Duffy Oct 27 '22 at 18:24
  • 2
    Also, the only character that can't exist in a file name is the NUL byte, so you should use `find -print0` and `readarray -d ''`. Neither spaces nor newlines are suitable. – Charles Duffy Oct 27 '22 at 18:25
  • Thanks, both. Simply removing `-d ' ' ` worked. – Lyam Oct 27 '22 at 18:47
  • 1
    [How can I store the "find" command results as an array in Bash](https://stackoverflow.com/q/23356779/3266847) has all bases covered for getting `find` output into an array. – Benjamin W. Oct 27 '22 at 18:53
  • @CharlesDuffy The slash character (`/`) also cannot exist in a `filename`. You probably meant `pathname`. – M. Nejat Aydin Oct 27 '22 at 20:18
  • Yes, obviously, since find emits pathnames unless a particular GNU extension is used to avoid that. – Charles Duffy Oct 28 '22 at 01:22

0 Answers0