Home > other >  How to find files matching a regex and save each result in an array?
How to find files matching a regex and save each result in an array?

Time:11-09

#!/bin/bash
result=$(find . -type f -name -regex '\w{8}[-]\w{4}[-]\w{4}[-]\w{4}[-]\w{12}')
echo $result

I tried the above but used a variable and I'm a bit lost.

CodePudding user response:

mapfile -td '' myarray \
< <(find . -type f -regextype egrep \
    -regex '.*/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}' -print0)

# iterate the array in a loop
for i in "${myarray[@]}"; do
    echo "$i"
done

Assuming you were looking for files matching this regex.

CodePudding user response:

I bet find uses basic regular expressions by default, so \w is probably not known, and the braces would have to be escaped. Add a -regextype option (and remove -name):

re='.*[[:alnum:]]{8}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{12}.*'
find . -type f -regextype egrep -regex "$re"

Note that my find man page says about -regex:

This is a match on the whole path, not a search.

Which means the leading and trailing .* are necessary to ensure the pattern matches the whole path.

And to capture the results into an array (assuming no newlines in the filenames), use the bash mapfile command, redirecting from a process substitution.

mapfile -t files < <(find . -type f -regextype egrep -regex "$re")
  • Related